Java文件未使用新行字符写入流 [英] Java file not written to stream with new line characters

查看:120
本文介绍了Java文件未使用新行字符写入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We're streaming a CSV file from a web service. It appears that we're losing the new line characters when streaming - the client gets the file all on a single line. Any idea what we're doing wrong?

代码:

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


推荐答案

不要使用的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.

这篇关于Java文件未使用新行字符写入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆