如何修改此run方法,不仅可以在输出窗口中打印srting,还可以在项目目录中写入文件,例如outfile.txt。此外,每个字符串应位于文件中的单独一行。
所以我已经在项目目录中创建了一个名为outfile.txt
的文件代码在窗口上打印正常但不在文本文件中打印的时刻
这是代码#
public void run() throws IOException
{
Scanner sc = new Scanner(System.in);
boolean cont = true;
while (cont) {
System.out.println("Enter text");
String s = sc.nextLine();
if ("*".equals(s)) {
cont = false;
} else {
String result = shorthand(s);
System.out.println(result);
PrintWriter pw = new PrintWriter("outfile.txt");
pw.println(result);
}
}
}
答案 0 :(得分:6)
写完后,您需要关闭打开的文件:
pw.Close();
答案 1 :(得分:1)
只需查看exampledot。
答案 2 :(得分:0)
您不应在java.io.File
内使用相对路径。它们将相对于当前工作目录,而后者又取决于您启动Java应用程序的方式。这可能不是您期望的项目目录。您应始终在java.io.File
中使用绝对路径。例如。 c:/path/to/outfile.txt
。
要了解当前实际的写入位置,请执行以下操作:
File file = new File("outfile.txt");
System.out.println(file.getAbsolutePath());
再一次,永远不要使用相对路径。始终使用绝对路径。不过只需将它放在类路径中并使用ClassLoader#getResource()
然后URL#toURI()
然后new File(uri)
。
事实上,关闭溪流。它将隐式刷新数据缓冲区到资源。
答案 3 :(得分:0)
你每次都在创作一个新的版画。考虑在循环之前制作它,就像这样
PrintWriter pw = new...
while(cond) {
...
pw.println(...);
pw.flush(); // do this too, it does the actual writing
}
pw.close();