gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:36 25 4
gpt4 key购买 nike

如何在不先关闭 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();
}
}

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

最佳答案

你还没有刷新流

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();
}
}

关于java - 在java中同时读取和写入同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com