Java文件未使用换行符写入流

Mar*_*eon 4 java streaming web-services file

我们正在从Web服务流式传输CSV文件.看来我们在流式传输时丢失了新行字符 - 客户端将文件全部放在一行上.知道我们做错了什么吗?

码:

 public static void writeFile(OutputStream out, File file) throws IOException {
    BufferedReader input = new BufferedReader(new FileReader(file)); //File input stream 
    String line;
    while ((line = input.readLine()) != null) { //Read file
        out.write(line.getBytes());  //Write to output stream 
        out.flush();
    }
    input.close();
} 
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 10

不要用BufferedReader.你已经OutputStream掌握了,所以只需获取一个InputStream文件并从输入中输出字节,然后以通常的Java IO方式输出它.这样你也不必担心被换掉的换行符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) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

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

为了提高性能多一点,你可以随时包裹InputStreamOutputStreamBufferedInputStreamBufferedOutputStream分别.


Nat*_*hes 6

readline方法使用换行符来分隔读取的内容,因此readLine不会返回换行符本身.

不要使用readline,如果需要,可以使用BufferedInputStream并一次读取一个字节的文件,或者将自己的缓冲区传递给OutputStream.write.

请注意,就像BalusC和Michael Borgwardt所说,Readers和Writers用于文本,如果你只想复制文件,你应该使用InputStream和OutputStream,你只关心字节.