I am trying to copy PDF files from any location in computer to resources directory in myProject (to be used later in my project) I followed all instruction in the following links:
open resource with relative path in java
How to copy file in resource folder in java
How to define a relative path in java
But I am getting always java.lang.NullPointerException
It is clear to me that I have problem with correct relative path. I am using 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
How can I define the correct relative path of "pdf" directory inside MyClass.java? Also what would be the best code for this case
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());
}
}