简体   繁体   English

使用Scanner Java读取文件即使目录正确也无法使用

[英]Read a file with Scanner Java doesn't work even with correct directory

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. \\t是转义序列。 You have to escape that backslash again. 您必须再次转义该反斜杠。 Try D:\\\\test.txt . 尝试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 . 请参阅Java文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM