在java中同时读取和写入同一个文件

时间:2018-06-19 09:39:23

标签: java file-io bufferedreader bufferedwriter

如果没有先关闭我的BufferedWriter,我如何访问文件中的数据?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Tp {
    public static void main(String[] args) throws IOException{
        File f = new File("Store.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        BufferedReader br = new BufferedReader(new  FileReader(f));
        bw.write("Some text");
        System.out.println(br.readLine());
        bw.write("Some more text");
        bw.close();
        br.close();
    }
}

控制台显示为null。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

你还没有刷新流

public class Tp {
  public static void main(String[] args) throws IOException{
    File f = new File("/path/to/your/file/filename.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    BufferedReader br = new BufferedReader(new  FileReader(f));
    bw.write("Some text");
    bw.flush();
    System.out.println(br.readLine());
    bw.write("Some more text");
    bw.flush();
    bw.close();
    br.close();
  }
}