从文件读取文本 IO 异常
我正在尝试从我的计算机驱动器 D:
中的文本文件中读取文本
因此,我用 Java 编写:
public class Test {
public static void main(String [] args ) throws IOException{
FileReader in= new FileReader("D:\nir");
BufferedReader bin= new BufferedReader(in);
String text = bin.readLine();
}
}
我收到此错误异常:
Exception in thread "main" java.io.FileNotFoundException: D:ir
(The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at A11.main(A11.java:14)
我不明白什么是错误,既然文件存在,名称就是正确的,也许我没有使用正确的语法和命令?
i'm trying to read text from a text file that I have in my computer in drive D:
So, I wrote in Java:
public class Test {
public static void main(String [] args ) throws IOException{
FileReader in= new FileReader("D:\nir");
BufferedReader bin= new BufferedReader(in);
String text = bin.readLine();
}
}
I'm getting this error exception:
Exception in thread "main" java.io.FileNotFoundException: D:ir
(The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at A11.main(A11.java:14)
I don't understand what is wrong, since the file exist, the name is correct, perhaps I don't use the correct syntax and commands?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是问题所在:
这是“D:”加上换行符+“ir”。
我认为你的意思是
基本上反斜杠需要在Java字符串文字中转义。请参阅Java 语言规范中的第 3.10.6 节 了解详情。
(顺便说一句,我个人不会使用
FileReader
,因为它始终使用平台默认编码,但这是一个单独的问题。)编辑:指定的替代方法>任一类型的斜杠都是使用
File
:这是最与平台无关的方法。
This is the problem:
That's "D:" plus a line feed + "ir".
I think you meant
Basically the backslash needs to be escaped in the Java string literal. See section 3.10.6 in the Java language specification for details.
(As an aside, personally I wouldn't use
FileReader
as it always uses the platform default encoding, but that's a separate issue.)EDIT: An alternative to specifying either kind of slash is to use
File
:That's the most platform-agnostic approach.
我认为,您应该首先检查文件是否存在。另请使用:D:\\file.txt
I think, you should first check if file is exists or not. Also use: D:\\file.txt
转义斜杠 \\ 或将斜杠的方向更改为 /。
我更喜欢改变方向。
所以你有
two三种可能性更新:看看你的异常,它说 D:ir 丢失了,看看斜杠和 n 是如何丢失的。 Java 已将您的 \n 转换为新行字符,这显然被 FileReader 忽略
Either escape the slash \\ or change direction of the slash to /.
I much prefer the change of directions.
So you have
twothree possibilitysUpdate: Look at your exception it says that D:ir is missing ,look how both the slash and n is missing. Java have transformed your \n to a new line character which obviously was ignored by the FileReader
以下代码避免或消除了文件分隔符的问题:
然后您可以像这样使用文件分隔符:
The following code avoids or eliminates issues with the file separator:
then you can use the file separator like this: