我正在尝试从文件中读取值并处理它们。 我有一个代码如下。即使文件的地址是正确的,它也无法找到该文件。
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)
异常。 我该怎么做?
答案 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.