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

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?

Code:

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

}

解决方案

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

}

}

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值