简体   繁体   中英

How to read, write content to text file using FileWriter and BufferedWriter in Java

I have a basic requirement of writing some text into a text file and read that text and print in Console.

What is the better approach? Is anything better(in terms of performance/usage) than BufferedReader or BufferedWriter for writing and reading simple text?

Can someone also suggest better way of writing the below code aswell:

public class FileReadWrite 
{
    public static void main(String[] args) throws IOException 
    {
        File objFile=new File("SampFile.txt");

        if(!objFile.exists())
            objFile.createNewFile();

        FileReader objFR=new FileReader(objFile);
        BufferedReader objBR=new BufferedReader(objFR);

        FileWriter objFW=new FileWriter(objFile);
        BufferedWriter objBW=new BufferedWriter(objFW);


        objBW.write("Hello World!!!");
        objBW.write("How Are you");
        objBW.close();

        String strContent;
        while((strContent=objBR.readLine())!=null)
            System.out.println(objBR.readLine());

        objBR.close();
    }
}

try printing the string you are reading in your while loop:

while((strContent=objBR.readLine())!=null)
        System.out.println(strContent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM