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.
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.
Append new line to the FileWriter on each iteration, but do it right, don't concatenate strings.
FileWriter fw=new FileWriter(file,true);
for(int i=25;i<30;i++){
fw.append(String.valueOf(i));
fw.append("\n");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With