从文件读取时出错(Java)

时间:2012-07-07 09:41:03

标签: java file-io filenotfoundexception

我在这里发布了一个类似的问题:Read from a file containing integers - java但是得不到合适的回复。

现在我编写了这个只读取文件并输出结果的新代码。

每当我尝试从文件中读取时,我都会收到FileNotFoundException。代码如下:

import java.io.*;

public class second {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    File f = new File("C:\\Users\\Haroon\\workspace\\ppp\\temperature.txt");
    FileReader file = new FileReader(f);
    BufferedReader buf = new BufferedReader(file);

    String s = null;
    while((s = buf.readLine()) != null){
        System.out.println(s);
    }
}

}

这很奇怪,因为该文件位于项目的文件夹中。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

那应该有用。转到文件的位置,复制路径,将其粘贴到代码中,然后转义斜杠。你错过了什么。

同时检查文件的名称/扩展名是否正确,您可以使用“temperature.txt.txt”之类的内容。

答案 1 :(得分:0)

我不知道为什么你无法阅读该文件。它在我的系统上正常工作。因为你让你在日食中投射。我会在这里发布一个解决方法。

System.out.println(System.getProperty("user.dir"));

使用此命令在执行时查找当前用户目录。现在直接将文件放在该用户目录中。现在,您可以直接通过其名称读取文件。 例如:

File f = new File("temperature.txt");

同样如'lxxx'所述,请在Windows中启用show file extension选项来检查文件名和扩展名。