且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java文件未使用新行字符写入流

更新时间:2023-12-03 20:31:17

不要使用的BufferedReader 。你手头已经有一个 OutputStream ,所以只需得到一个 InputStream 的文件,并将输入到输出的字节输出它是通常的Java IO方式。这样你也不必担心 BufferedReader 吃掉换行符:

Don't use BufferedReader. You already have an OutputStream at hands, so just get an InputStream of the file and pipe the bytes from input to output it the usual Java IO way. This way you also don't need to worry about newlines being eaten by BufferedReader:

public static void writeFile(OutputStream output, File file) throws IOException {
    InputStream input = null;
    byte[] buffer = new byte[10240]; // 10KB.
    try {
        input = new FileInputStream(file);
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
}

使用 Reader / Writer 将涉及字符编码问题如果您事先不知道/指定编码。你实际上也不需要在这里了解它们。所以请把它放在一边。

Using a Reader/Writer would involve character encoding problems if you don't know/specify the encoding beforehand. You actually also don't need to know about them here. So just leave it aside.

为了提高性能,你可以随时包装 InputStream OutputStream 分别在 BufferedInputStream BufferedOutputStream 中。

To improve performance a bit more, you can always wrap the InputStream and OutputStream in an BufferedInputStream and BufferedOutputStream respectively.