简体   繁体   中英

How to read the first line of a text file in java and print it out?

I want to save a state by write into a file and then read the file later with bufferedReader to get the state again. Here is my code:

public static void main(String[] args) throws IOException{

   FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
   BufferedWriter save = new BufferedWriter(fw);

   save.write("helloWorld");

   BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));

   System.out.println(r.readLine());

   save.close();        
}

If I press run, I got printed out null . I tried it with:

if(r.readLine() != null){
    System.out.println(r.readLine());
}

But logically it prints me out nothing now. I don't know what I am doing wrong here. Can you help me please?

A BufferedWriter buffers output until you flush the stream you write to so you need to flush the stream by either closing the file or using save.flush() .

 public static void main(String[] args) throws IOException {

        FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
        BufferedWriter save = new BufferedWriter(fw);

        save.write("helloWorld");
        save.flush();  // this writes the bytes in the stream to the file.

        BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));

        System.out.println(r.readLine());

        save.close();
    }
  // Write to file      
  FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
  BufferedWriter save = new BufferedWriter(fw);

  save.write("example");
  save.flush()

  // read as stream
  BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));
  System.out.println(r.readLine());

  save.close();

When writing to a file with a BufferedWriter, the content is not directly written to disk, as it is obviously buffered. You should flush the content as @ludo_rj suggested in his answer.

Better yet is to close the writer as early as possible, which will automatically flush the content. Closing the reader is also necessary, by the way.

You should go with the following mechanism (I have distributed the approach into several methods to make it more clear):

public class SaveStateTesing {

    private static final String FILE_NAME = "C:\\Users\\Nicolas\\Desktop\\save.txt";

    public static void main(String[] args) throws IOException {
        saveState("helloWorld", FILE_NAME);
        String state = readState(FILE_NAME);
        System.out.println(state);
    }

    private static void saveState(String state, String fileName) throws IOException {
        try(PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {
            writer.println(state);
        }
    }

    private static String readState(String fileName) throws IOException {
        try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            return reader.readLine();
        }
    }

}

Note, that I used the try-with-resource statement, only available in Java 7 (and 8, of course). If you are running it in an older Java version, you must write the methods as following:

    private static void saveState(String state, String fileName) throws IOException {
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
            writer.println(state);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    private static String readState(String fileName) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileName));
            return reader.readLine();
        } finally {
            if (reader != null)
                reader.close();
        }
    }

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