java - FileWriter 和 PrintWriter 不会输出到文件

标签 java flush filewriter printwriter println

我有这个代码

public User createnewproflie() throws IOException
{
    FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
    PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
    String filename= "users.txt";
    Scanner userFile = new Scanner(filename); //creates new obj that reads from file
    User usr=new User(); //creates new user istance
    String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname

    userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0");     //writes usrname in file
    userfile.flush();
    usr.setName(usrname); //gives usr the selected usname

    return usr;
}

并且它没有输出到文件中...有人可以帮忙吗? 我知道刷新会输出所有缓冲的文本,但由于某些奇怪的原因它似乎不起作用......

最佳答案

您可以将 StringFileWriter 一起使用,但 Scanner(String) 生成从指定字符串(而不是从文件)扫描的值。将 File 传递给 Scanner 构造函数(最好将相同的 File 传递给 FileWriter) 。并且您需要 close() 才能读取它;也许有try-with-resources

File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
    PrintWriter userfile = new PrintWriter(fwriter);) {
    // ... Write stuff to userfile
} catch (Exception e) {
    e.printStackTrace();
}
Scanner userFile = new Scanner(f);

最后,我通常更喜欢类似 File f = new File(System.getProperty("user.home"), "user.txt"); 这样文件就保存在用户中主目录。

关于java - FileWriter 和 PrintWriter 不会输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220044/

相关文章:

java - 文件编写器如何停止从文件中写入文本

java - Spring 编译时和运行时注解的区别

java - 微小的图像,没有旋转,但仍然得到 OutOfMemoryError : bitmap size exceeds VM budget

mysql - 什么是最积极的 FLUSH/RESET mysql 命令来清除查询缓存(以及其他任何...)

go - 何时在 Go 中刷新文件?

java - 写入新文件时自动创建完整路径

Java FileWriter 不写入文件

java xslt教程

Java 调试困惑

php - ob_implicit_flush(), flush(), ob_flush() - 不在远程服务器上工作