我的智慧在这里结束,我和一位朋友一直试图获取用户输入并将其写入.txt文件,但我不知道我哪里出错......
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:
答案 0 :(得分:2)
完成后,您可以使用try-with-resources
至close
;你可能会使用break
之类的无限循环
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();
}
}
答案 1 :(得分:0)
你必须添加,
pw.println(str);
在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();
之后
并希望一次又一次地将其放入while循环中,
expode()