将Java中的长字符串写入文件
我正在尝试将一个大整数数组(10 000 个元素)转储到文本文件中,但遇到了一些问题。我尝试了两种不同的方法,但似乎都不起作用。下面是我编写的函数:
private static void writeToFile(String name, int[] a){
try {
FileWriter fw = new FileWriter(name);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("working");
for (int n: a){
bw.write(n + " ");
}
bw.close();
} catch (IOException e) {
System.err.print("Unable to write to file " + name+ ".");
e.printStackTrace();
}
}
我尝试的第一件事是在 for 循环中创建一个字符串,然后将整个字符串写入文件。这两种方法都不起作用,并给出了相同的结果,如下所示:
- 文件已创建但留空
- 对于较短的数组(〜10个元素)
- 工作正常如果空格是字母,例如:bw.write(n +“a”)
任何想法我做错了什么?或者还有我没有看到的更简单的方法吗?
谢谢,
西瓦特里克斯
I'm trying to dump a large integer array (10 000 elements) into a text file but am encountering some problems. I've tried two different approaches and neither seems to be working. Below is the function I've written:
private static void writeToFile(String name, int[] a){
try {
FileWriter fw = new FileWriter(name);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("working");
for (int n: a){
bw.write(n + " ");
}
bw.close();
} catch (IOException e) {
System.err.print("Unable to write to file " + name+ ".");
e.printStackTrace();
}
}
The first thing I tried was creating a string in the for loop and then writing the whole string to the file. Neither method works and gives me the same results as follows:
- File is created but left blank
- Works fine for shorter arrays (~10 elements)
- Works fine if the space is a letter eg: bw.write(n + "a")
Any idea what I'm doing wrong? Or is there an even easier way that I'm not seeing?
Thanks,
Civatrix
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您能解释一下您之后如何查看/阅读文件吗?据我所知,您的代码基本上很好(禁止将 close() 移动到finally块),并且无论添加空格还是其他字母,它实际上应该没有任何区别。但这可能会对文本编辑器产生影响,我想......?
Can you explain how you're viewing/reading in the file afterwards? Your code is basically fine as far as I can see (bar moving the close() to a finally block), and it really should make no difference whatsoever whether a space or other letter is added. But that might make a difference e.g. to a text editor, I suppose...?
该代码会将
a[]
的所有元素写入文件,后跟一个空格,除非出现异常。但是它不会写任何行。这是你的问题吗?如果是这样,则在每个write()
之后需要bw.newLine()
。That code will write all the elements of
a[]
to the file followed by a space, unless it gets an exception. However it won't write any lines. Is that your problem? If so, you needbw.newLine()
after eachwrite()
.