문제

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)
도움이 되었습니까?

해결책

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);
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top