Java 需要将字符串输出到.txt文件
我在这里束手无策,我和一个朋友一直试图获得用户输入并将其写入.txt文件,但我不知道哪里出了问题Java 需要将字符串输出到.txt文件,java,Java,我在这里束手无策,我和一个朋友一直试图获得用户输入并将其写入.txt文件,但我不知道哪里出了问题 public static void main (String [] args) { toTxtFile(); } static void toTxtFile() { //Scanner in = new Scanner (System.in); try { File records = new File("C:\\Users\\rodrisc
public static void main (String [] args)
{
toTxtFile();
}
static void toTxtFile()
{
//Scanner in = new Scanner (System.in);
try
{
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
records.createNewFile();
FileWriter fw = new FileWriter(records, true);
PrintWriter pw = new PrintWriter(fw);
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
pw.println(str);
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
pw.flush();
pw.close();
//in.close();
}
else
{
pw.println(str);
toTxtFile();
}
}
catch (IOException exc)
{
exc.printStackTrace();
}
}
}
我已经尝试过将循环作为一个do/while,但效果并不好,任何帮助都将不胜感激。D:完成后,您可以使用a来关闭;您可以使用带有中断的无限循环
static void toTxtFile() {
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
try (PrintWriter pw = new PrintWriter(records)) {
while (true) {
String str = JOptionPane.showInputDialog(null, "Enter your text below");
str = str.toUpperCase();
if (str.equals("END")) {
JOptionPane.showMessageDialog(null, "You've ended the task",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
你必须补充一点
pw.flush();
后pw.println(str)代码>
想一次又一次地做,然后同样地把它放到while循环中
while(true){
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str); // else write to file...
pw.flush();
}
pw.flush();
pw.close();
很明显你没有关闭pw
?为什么要为每个方法调用创建新的方法调用,但只关闭最后一个方法调用?其他的应该保持打开?我不知道,但不管怎样都没关系,我刚刚用do/while解决了这个问题,谢谢你的输入