java中的FileWriter没有写入txt文件 [英] FileWriter in java not writing to txt file

查看:141
本文介绍了java中的FileWriter没有写入txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 JOptionPane 获取输入,并使用 FileWriter class。为了确保输入用户键入的内容,我写了一个system.out,然后出现了我在JOptionPane中输入的内容。不幸的是,当我打开.txt文件时,我输入的内容就出现了!顺便说一句,我输入的文件路径是正确的。

I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.

这是我的代码。帮助我!

Here is my code. HELP ME!

String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
    FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
    BufferedWriter out = new BufferedWriter(charectersname);
    out.write(playername);
    }
catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}


推荐答案

缓冲编写者只会写出来当它们已满或当它们被关闭时(因此名称​​缓冲)。

Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).

所以你可以这样做:

out.close();

将刷新缓冲区然后关闭它。如果您只想刷新它但是保持打开以进行进一步的写入(例如,假设您正在编写日志文件),您可以这样做:

which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:

out.flush();

在完成此类资源时,您可能希望这样做。例如

You'd likely want to do this when finishing up with such a resource. e.g.

BufferedWriter out = ...
try {
   out.write(...);
}
catch (Exception e) {
   // ..
}
finally {
   out.close();
}

或者可能使用 try-with-resources 构造,(坦率地说)编写代码更加可靠。

Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.

这篇关于java中的FileWriter没有写入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆