将数组写入文件
好的,我已经上课了(对格式感到抱歉,不太熟悉该网站)
import java.io.*;
public class writingArray
{
public static void writeToFile(String fileName, String[] input) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(new FileOutputStream(fileName, true));
int length = input.length;
int i;
for(i = 0; ++i < length; i++) {
printWriter.println(input[i]);
}
printWriter.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
问题是我想将一个数组写入一个文件,每个条目都在单独的行上,并且我想擦除该文件从每次写入开始。有什么建议吗?因为我所能做的就是写入数组的最后一个条目,同时擦除所有先前的条目,但我可以在最后一个条目下方多次写入。
谢谢^^
Okay so I've got my class ( sorry about the formatting, not too familiar with the site )
import java.io.*;
public class writingArray
{
public static void writeToFile(String fileName, String[] input) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(new FileOutputStream(fileName, true));
int length = input.length;
int i;
for(i = 0; ++i < length; i++) {
printWriter.println(input[i]);
}
printWriter.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
The problem is I want to write an array to a file with each entry being on a separate line and I want to wipe the file at the start from each write. Any advice on what to do? Because all I've managed to do is write the last entry of the array while wiping all the previous entries and yet I can write the last entry several times below itself.
Thanks ^^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你不想将 i 增加两次。摆脱 ++i。
I don't think you want to increase i twice. Get rid of the ++i.
我强烈建议使用库 http://commons .apache.org/io/api-release/org/apache/commons/io/FileUtils.html 已经解决了其中许多问题。如果将数组转换为列表,您可以使用:
该库的作者想到了大多数人没有想到的许多问题,例如行结束、编码、错误捕获等。它对于一般用途也可能尽可能高效。
I strongly recommend using the library http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html which has already tackled many of these problems. If you transform your array to a List you can use:
The authors of the library have thought of many problems that most people don't such as line-endings, encodings, error trapping, etc. It's also likely to be as efficient as possible for general use.
for(i = 0; ++i < length; i++) {
看起来不错,应该是for(i = 0; i < length; i++) {
> ?或者,甚至更好: for (String line : input) { }
另外,new FileOutputStream(fileName, true) 不会清除文件,而是追加到文件中。
for(i = 0; ++i < length; i++) {
does look right, should this befor(i = 0; i < length; i++) {
?Or, even better:
for (String line : input) { }
Also,
new FileOutputStream(fileName, true)
will not clear the file, rather append to it.