如何解决如何使用Java在文件中逐行写入内容
如何将所有输出逐行写入txt文件?下面的代码段仅写了1行。基本上,我希望将random_no逐行写入txt文件。
public static void main(String args[]) throws FileNotFoundException,IOException {
HashSet <Integer> newset = new HashSet <Integer>();
FileOutputStream fo = null;
for(int i =0;i<100;i++){
double d=Math.random()*10000;
//System.out.println(d);
String random_no= Integer.toString((int)d);
newset.add((int)d));
fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt" );
fo.write(random_no.getBytes();
}
fo.close();
System.out.println("Size is : " +newset.size());
解决方法
在这里您需要做两件事:
a)在循环外打开文件
b)在每个数字后写换行符
public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream("D:\\Test_No.txt");
HashSet<Integer> newset = new HashSet <Integer>();
for (int i = 0; i < 100; i++) {
double d = Math.random() * 10000;
// System.out.println(d);
String random_no = Integer.toString((int) d);
newset.add((int)d);
fo.write(random_no.getBytes());
fo.write("\n".getBytes());
}
fo.close();
}
,
您要在循环中打开文件,请尝试:
public static void main(String args[]) throws FileNotFoundException,IOException {
HashSet <Integer> newset = new HashSet <Integer>();
FileOutputStream fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt" );
for(int i =0;i<100;i++){
double d=Math.random()*10000;
//System.out.println(d);
String random_no= Integer.toString((int)d) + System.lineSeparator();
newset.add((int)d);
fo.write(random_no.getBytes());
}
fo.close();
System.out.println("Size is : " +newset.size());
}
您可能还需要考虑自动处理关闭:
public static void main(String args[]) throws FileNotFoundException,IOException {
HashSet <Integer> newset = new HashSet <Integer>();
try (FileOutputStream fo = new FileOutputStream("E:\\Test\\Files\\Test_No.txt" )) {
for(int i =0;i<100;i++){
double d=Math.random()*10000;
//System.out.println(d);
String random_no= Integer.toString((int)d) + System.lineSeparator();
newset.add((int)d);
fo.write(random_no.getBytes());
}
}
System.out.println("Size is : " +newset.size());
}
,
FileOutputStream
应该在循环外部初始化。
此外,要打印新行,还可以使用BufferedWriter
代替FileOutputStream
。
BufferedWriter
为您提供了BufferedWriter.newLine()
的选项,它可以处理与环境(Windows,Unix等)无关的新行。
public static void main(String args[]) throws IOException {
HashSet<Integer> newset = new HashSet<>();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("Test_No.txt",true));
for (int i = 0; i < 100; i++) {
double d = Math.random() * 10000;
String random_no = Integer.toString((int) d);
newset.add((int) d);
bufferedWriter.write(random_no);
bufferedWriter.newLine();
}
bufferedWriter.close();
System.out.println("Size is : " + newset.size());
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。