使用Scanner读取文件即使使用正确的目录,Java也无法正常工作

时间:2014-12-09 22:52:04

标签: java eclipse file

我正在尝试从文件中读取值并处理它们。 我有一个代码如下。即使文件的地址是正确的,它也无法找到该文件。

private Scanner x;

public void openFile()
{
    try{

        x = new Scanner(new File("D:\test.txt"));
    }
    catch(Exception e)
    {
        System.out.println("no such a file found");
    }
}


public void readFile()
{
    while(x.hasNext())   // ERROR LINE
    { 
        String a = x.next();
        String b = x.next();
        String c = x.next();
System.out.printf("%s %s %s\n",a,b,c);      
    }

}

public void closeFile()
{
    x.close();
}

}
public class readTest {

public static void main(String[] args){
ReadFile r = new ReadFile();
r.openFile();
r.readFile(); //ERROR LINE
r.closeFile();
}
}

我得到了

     no such a file found
     Exception in thread "main" java.lang.NullPointerException
     at ReadFile.readFile(ReadFile.java:23)
     at readTest.main(readTest.java:7)

异常。 我该怎么做?

1 个答案:

答案 0 :(得分:1)

\t是一个逃避序列。你必须再次逃避反斜杠。试试D:\\test.txt

  

以反斜杠\开头的字符是转义序列并具有   对编译器有特殊意义。

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

请参阅the Java documentation