PrintWriter 输出文件不存在,尽管没有抛出异常
PrintWriter the output file is not there although no exception thrown
我刚刚开始学习 Java,我遇到了以下问题,我已经为此苦苦挣扎了几个小时。我想使用 PrintWriter
来生成一个简单的文本文件。
我没有得到任何运行时异常,文件仍然没有出现在指定的目录中。
public class Main {
public static void main(String[] args) {
try (final PrintWriter writer = new PrintWriter(
new File("c:\test\new\notes.txt"))) {
writer.write("Test note");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
我做错了什么?
\
表示一个转义字符,因此需要对文字反斜杠字符进行转义。您还可以使用 /
和 Java 将为平台解析正确的分隔字符
try (final PrintWriter writer = new PrintWriter("c:\test\new\notes.txt")) {
在 writer.write("Test note")
之后添加 writer.flush()
,并为 Windows 路径使用双反斜杠(如其他答案所建议的那样)。
正如 Reimeus 所说,\
是 java 中的转义字符。
这意味着包含 "\n"
或 "\t"
的字符串不代表字符串文字 \n 或 \t!
'\n'
表示换行符,'\t'
表示制表符!
为了更好的理解,代码如下:
System.out.println("c:\test\new\notes.txt");
不会将 c:\test\new\notes.txt
打印到控制台,它会打印
c: est
ew
otes.txt
到控制台!
为了能够在字符串中写入反斜杠,您需要使用 '\'
!
我认为你的问题分为两部分:
- 为什么代码不起作用?
- 为什么没有抛出异常?
第一个问题已经回答了,但我认为第二个问题的答案至少同样重要,因为如果写入文件有任何问题,您当前的代码仍然会静默失败。
来自 PrintWriter (http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html) 的文档:
Methods in this class never throw I/O exceptions, although some of its
constructors may. The client may inquire as to whether any errors have
occurred by invoking checkError().
因此,您必须在 每次 调用 PrintWriter 方法之后调用 checkerror()
,否则您的代码将不可靠。
我刚刚开始学习 Java,我遇到了以下问题,我已经为此苦苦挣扎了几个小时。我想使用 PrintWriter
来生成一个简单的文本文件。
我没有得到任何运行时异常,文件仍然没有出现在指定的目录中。
public class Main {
public static void main(String[] args) {
try (final PrintWriter writer = new PrintWriter(
new File("c:\test\new\notes.txt"))) {
writer.write("Test note");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
我做错了什么?
\
表示一个转义字符,因此需要对文字反斜杠字符进行转义。您还可以使用 /
和 Java 将为平台解析正确的分隔字符
try (final PrintWriter writer = new PrintWriter("c:\test\new\notes.txt")) {
在 writer.write("Test note")
之后添加 writer.flush()
,并为 Windows 路径使用双反斜杠(如其他答案所建议的那样)。
正如 Reimeus 所说,\
是 java 中的转义字符。
这意味着包含 "\n"
或 "\t"
的字符串不代表字符串文字 \n 或 \t!
'\n'
表示换行符,'\t'
表示制表符!
为了更好的理解,代码如下:
System.out.println("c:\test\new\notes.txt");
不会将 c:\test\new\notes.txt
打印到控制台,它会打印
c: est
ew
otes.txt
到控制台!
为了能够在字符串中写入反斜杠,您需要使用 '\'
!
我认为你的问题分为两部分:
- 为什么代码不起作用?
- 为什么没有抛出异常?
第一个问题已经回答了,但我认为第二个问题的答案至少同样重要,因为如果写入文件有任何问题,您当前的代码仍然会静默失败。
来自 PrintWriter (http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html) 的文档:
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
因此,您必须在 每次 调用 PrintWriter 方法之后调用 checkerror()
,否则您的代码将不可靠。