Question

I've been trying to get a file in java from a internal to a external location. The file is copying but its not transferring the bytes. The file is originally 98 bytes and when transferred then set to 0. If you could tell me what im doing wrong or help me in any sort of way that would be great.

    private static void copyFile(String internal, File external) {
    InputStream stream = FileManager.class.getResourceAsStream(internal);
    if(stream == null) {
        System.err.println("Error: File not found when trying to copy at location " + internal);
    }
    OutputStream resStreamOut = null;
    int readBytes;
    byte[] buffer = new byte[4096];
    try {
        resStreamOut = new FileOutputStream(external);
        while((readBytes = stream.read(buffer)) > 0) {
            resStreamOut.write(buffer, 0 , readBytes);
        }

    } catch(IOException e1) {
        e1.printStackTrace();
        System.exit(1);
    } finally {
        try {
        stream.close();
        resStreamOut.close();
        } catch(IOException e2) {
            e2.printStackTrace();
            System.exit(1);
        }

    }

}

Edit:

Getting null pointer:

4.4.0 Error: File not found when trying to copy at location /res/shaders/basicFragment.fs
Exception in thread "main" java.lang.NullPointerException at
com.thinmatrix.konilax.handlers.FileManager.copyFile(FileManager.java:80) at
com.thinmatrix.konilax.handlers.FileManager.update(FileManager.java:56) at
com.thinmatrix.konilax.MainComponent.<init>(MainComponent.java:22) at
com.thinmatrix.konilax.MainComponent.main(MainComponent.java:115)
Was it helpful?

Solution

Only read the file if your code manages to open it (note the else statement when testing if your stream is null):

private static void copyFile(String internal, File external) {
    InputStream stream = FileManager.class.getResourceAsStream(internal);
    if(stream == null) {
        System.err.println("Error: File not found when trying to copy at location " + internal);
    } else {
        OutputStream resStreamOut = null;
        int readBytes;
        byte[] buffer = new byte[4096];
        try {
            resStreamOut = new FileOutputStream(external);
            while((readBytes = stream.read(buffer)) > 0) {
                resStreamOut.write(buffer, 0 , readBytes);
            }
        } catch(IOException e1) {
            e1.printStackTrace();
            System.exit(1);
        } finally {
            try {
                stream.close();
                resStreamOut.close();
            } catch(IOException e2) {
                e2.printStackTrace();
                System.exit(1);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top