我有这个代码
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;
}
并且它没有输出到文件中...有人可以帮忙吗? 我知道刷新会输出所有缓冲的文本,但由于某些奇怪的原因它似乎不起作用......
最佳答案
您可以将 String
与 FileWriter
一起使用,但 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/