我正在尝试将PDF文件从计算机中的任何位置复制到myProject中的资源目录(稍后在我的项目中使用) 我按照以下链接中的所有说明进行操作:
open resource with relative path in java
How to copy file in resource folder in java
How to define a relative path in java
但我总是得到java.lang.NullPointerException
我很清楚我的正确相对路径有问题。 我正在使用NetBeans IDE
MyProject/src/main/java/org/company/office/MyClass.java ---> java class
MyProject/src/main/resources/pdf/ ---> here I want to copy the PDF files
如何定义" pdf"的正确相对路径? MyClass.java里面的目录? 这个案例的最佳代码是什么
public void copyFile(String fileName, InputStream in) {
ClassLoader loader = Upload.class.getClassLoader();
File file = new File(loader.getResource("resources/pdf/"+ fileName).getFile());
//File file = new File(loader.getResource("pdf/"+ fileName).getFile());
System.out.println("file.getAbsoluteFile() " + file.getAbsoluteFile());
try {
try ( // write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(file)) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
}
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}