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

标签 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)

异常。 我该怎么做?

最佳答案

\t 是转义序列。你必须再次逃避那个反斜杠。尝试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.

参见the Java documentation .

关于java - 即使目录正确,使用 Scanner Java 读取文件也无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27390393/

相关文章:

android - 使用InputStream和Scanner android从.txt文件读取数据

java - 什么是 Java 中的参数多态性(附示例)?

java - 通过另一个类中的列表输出数据库信息 - Eclipse Android SQLite

python - PyDev 代码分析在 Aptana Studio 中不起作用

java - 通过检查 WSDL 文件确定 Web 服务中可用的方法

java - 如何在java中替换现有文本文件中的单词

Java/hibernate : how to write DAO code for complex SQLs

java - 无法找出简单 Java 应用程序的编译错误

java - 在哪里编写项目级 JavaDocs

斯卡拉 : bug with getLines?