Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Write to text file in java

Tags:

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.

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.

like image 392
vashishatashu Avatar asked Oct 21 '22 20:10

vashishatashu


1 Answers

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"); 
}
like image 165
SergeyB Avatar answered Oct 24 '22 11:10

SergeyB