I am trying to read values from a file and process them. I have a code as below. Even the address of the file is correct, it can't find the 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();
}
}
I got the
no such a file found
Exception in thread "main" java.lang.NullPointerException
at ReadFile.readFile(ReadFile.java:23)
at readTest.main(readTest.java:7)
exception. How should i do that ?
\\t
is an escape seqence. You have to escape that backslash again. Try D:\\\\test.txt
.
A character preceded by a backslash \\ is an escape sequence and has special meaning to the compiler.
\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.
See the Java documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.