[英]Read and Write to text file in java
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.
但是当我看到文件中的值时,我得到了一个直线模式: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存储如何工作,所以请给出一些链接。
try this. 试试这个。 add manually a new line..
手动添加新行..
fw.append(String.valueOf(i)+"\n");
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
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.