在java中读取和写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20203751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read and Write to text file in java
提问by vashishatashu
I'm trying to add values in a textfile. Its working well and output is good in eclipse. But when i see the values in file, i get a straight pattern : 2526272829.
我正在尝试在文本文件中添加值。它运行良好,在 eclipse 中的输出也很好。但是当我看到文件中的值时,我得到了一个直线模式:2526272829。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileDemo {
public static void main(String[] args) throws IOException {
BufferedReader bfr;
String line;
bfr=new BufferedReader(new InputStreamReader(System.in));
String fileName=bfr.readLine();
File file=new File(fileName);
if(!file.exists()){
file.createNewFile();
}
try{
bfr=new BufferedReader(new FileReader(file));
while((line=bfr.readLine())!=null){
System.out.println(line);
}
FileWriter fw=new FileWriter(file,true);
for(int i=25;i<30;i++){
fw.append(String.valueOf(i));
}
while((line=bfr.readLine())!=null){
System.out.println(line);
}
bfr.close();
fw.close();
}catch(FileNotFoundException fex){
fex.printStackTrace();
}
}
}
and i also want to know how bufferedReader storage works so please give some links.
我也想知道 bufferedReader 存储是如何工作的,所以请提供一些链接。
采纳答案by SergeyB
Append new line to the FileWriter on each iteration, but do it right, don't concatenate strings.
在每次迭代时向 FileWriter 追加新行,但要正确操作,不要连接字符串。
FileWriter fw=new FileWriter(file,true);
for(int i=25;i<30;i++){
fw.append(String.valueOf(i));
fw.append("\n");
}
回答by subash
try this. add manually a new line..
尝试这个。手动添加一个新行..
fw.append(String.valueOf(i)+"\n");
回答by user3027681
You need to add a newline character in your for loop:
您需要在 for 循环中添加换行符:
FileWriter fw=new FileWriter(file,true);
for(int i=25;i<30;i++){
fw.append(String.valueOf(i)+"\n"); //Here I've made the small correction
}
This will write on a new line each time you append. I'm assuming this is the output you wanted.
每次追加时,这将写在新行上。我假设这是您想要的输出。
For bufferedReader information you can look here for more information:
有关 bufferedReader 信息,您可以在此处查看更多信息:
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html