开发者

IO exception reading text from a file

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.File开发者_Python百科Reader.<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?


This is the problem:

new FileReader("D:\nir")

That's "D:" plus a line feed + "ir".

I think you meant

new FileReader("D:\\nir")

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:

File file = new File("D:", "nir.txt");

That's the most platform-agnostic approach.


I think, you should first check if file is exists or not. Also use: D:\\file.txt

File file = new File(fileName);
if (file.exists()) {
    FileReader rader = new FileReader("D:\\file.txt");      
}


Either escape the slash \\ or change direction of the slash to /. I much prefer the change of directions.

So you have two three possibilitys

FileReader in= new FileReader("D:\nir"); // Won't work as \ is an escape character

FileReader in= new FileReader("D:\\nir"); // Escaping, works but not my preferred way

FileReader in= new FileReader("D:/nir"); // I prefer this

FileReader in= new FileReader(new File("D:", "nir.txt")); // Update with help from Jon skeets nice find.

Update: 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:

import static java.io.File.separator;

then you can use the file separator like this:

final File test_file = new java.io.File("D:" + separator + "nir");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜