Java IO复制文件

时间:2014-04-03 23:24:34

标签: java java-io

我一直在尝试从内部到外部位置获取java文件。该文件正在复制但不传输字节。该文件最初是98个字节,当转移时,然后设置为0.如果你能告诉我我做错了什么或以任何方式帮助我,这将是伟大的。

    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);
        }

    }

}

修改

获取空指针:

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)

1 个答案:

答案 0 :(得分:1)

如果您的代码设法打开它,则只读取该文件(在测试您的流是否为null时请注意else语句):

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);
            }
        }
    }
}