简体   繁体   English

如何使用Java将巨大的字符串写入文件

[英]How write huge string to file using java

So basically I have: 所以基本上我有:

FileOutputStream fos = new FileOutputStream(dir + "/" + name);
fos.write(bImg);
fos.close();

Now here sometimes bImg could contains more than 5MB which I happen to get performance problem. 现在,有时bImg可能包含超过5MB bImg ,而我碰巧遇到了性能问题。 So I might need to write part to part of the string to the file. 因此,我可能需要将部分字符串写入文件。 Something like writing 5000 chars to the file first then got to next 5000 chars and so on. 例如先写入5000个字符,然后再写入下5000个字符,依此类推。 But I don't really know how to do that. 但是我真的不知道该怎么做。

Tried: 尝试过:

String file = dir + "/" + name;
FileOutputStream fos = new FileOutputStream(new File(file));
BufferedOutputStream buffOut=new BufferedOutputStream(fos);

buffOut.write(bImg); 

buffOut.flush();
buffOut.close();

But no luck still having same problem 但是没有运气仍然有同样的问题

You need to wrap the output string in a BufferedOutputStream. 您需要将输出字符串包装在BufferedOutputStream中。 It will handle writing the data in chunks for you. 它将为您分块处理数据。 Remember to flush the BufferedOutputStream when you're done so that all data ends up in your file. 记住在完成后刷新BufferedOutputStream,以便所有数据最终存储在文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM