0

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());
    }
}
R.Almoued
  • 219
  • 6
  • 16
  • The `resources` folder exists only in your develop environment. The correct relative path is `"/pdf/"+filename` (including leading `/`) – Timothy Truckle Jan 15 '18 at 14:52
  • @TimothyTruckle I tried to change it, but I got this: WebappClassLoader context: \Wirote delegate: false repositories: \WEB-INF\classes\ ----------> Parent Classloader: java.net.URLClassLoader@372f7a8d myPDF.pdf (The filename, directory name, or volume label syntax is incorrect) – R.Almoued Jan 15 '18 at 15:08
  • don't use `getClassLoader()` it is only needed if you want to access resources outside the class path. `getClass().getResource("path")` will do. – Timothy Truckle Jan 15 '18 at 15:56
  • @TimothyTruckle I used: System.out.println("getClass().getResource("/pdf/"+ fileName)); The result is: file:/D:/Users/ralmoued/Documents/NetBeansProjects/MyProject/target/awv-seite/WEB-INF/classes/pdf/2017-November.pdf. But it is not correct. It should be: D:\Users\ralmoued\Documents\NetBeansProjects\MyProject\src\main\resources\pdf\2017-November.pdf – R.Almoued Jan 16 '18 at 14:12

0 Answers0