我对 Java 和 Netbeans 还比较陌生。我想要做的是打开“bloodreports.resources”包内的这个 Word 文档文件。
我尝试从那里打开它的原因是因为我认为一旦构建了可运行的 JAR 文件,我在何处以及在哪台机器上运行 JAR 文件就不再重要了;资源永远都在。
有更好的方法吗?难道我错了?
在过去的一个小时里我一直在努力让它工作......非常感谢任何帮助!
我尝试了以下代码:
public class WordDocumentHandler {
public static void main(String[]args){
String path = "/resources/bloodreportformat.docx";
File file = new File(path);
if(file.exists()){
System.out.println("Exists");
}
}
}
“存在”这个词永远不会被打印出来。我做错了什么?
您正在尝试访问 Netbeans 中的资源。正如@user207421所说,您无法像以前那样访问资源,因为资源不是文件。您需要使用
getResource()
函数来解决您的问题。修改后的代码:
public class WordDocumentHandler {
public static void main(String[]args){
String resource_path = "/resources/bloodreportformat.docx";
URL resource_url = WordDocumentHandler.class.getResource(resource_path); //Use this function
//Check if the file exists
if (resource_url != null) {
System.out.println("Exists");
//Other code
}
}
}
getResource()
函数返回您尝试访问的资源的URL。获得 URL 后,您就可以访问该资源。
在 Java 项目中使用资源时,文件路径的处理方式与典型文件路径不同。
在 Java 中,当您访问 JAR(或资源文件夹中)中的文件时,您不能像处理文件系统上的常规文件路径那样直接将其视为 File 对象。相反,您需要使用
getResource()
方法从 JAR 文件中访问资源:
public static void main(String[] args) {
String path = "/bloodreports/resources/bloodreportformat.docx";
// Get the URL of the resource
URL url = WordDocumentHandler.class.getResource(path);
if (url != null) {
System.out.println("Exists");
// Now you can use this URL to access the resource
// For example, if you want to create a File object, you can do:
File file = new File(url.getFile());
// Do whatever operations you need with this file
} else {
System.out.println("Does not exist");
}
}