我正在使用nio2使用eclipse读取桌面中的外部文件。我收到以下代码的异常。

java.nio.file.NoSuchFileExceptionC:\Users\User\Desktop\JEE\FirstFolder\first.txt

请指教如何解决呢?也尝试使用命令提示符。得到同样的异常。

public class ReadingExternalFile {

    public static void main(String[] args) {

        Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
        System.out.println(p1.toString());
        System.out.println(p1.getRoot());

        try(InputStream in = Files.newInputStream(p1);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
            {
            System.out.println("Inside try");
            String line=null;
            while((line=reader.readLine())!=null){
                if (!line.equals("")) {
                    System.out.println(line);
                    }
                //System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println( e);
        }
    }
}

最佳答案

我不明白为什么要使用Path对象,您可以简单地使用File对象并仅使用字符串作为路径来制作文件,然后将其包装在文件读取器对象中,然后将其包装在缓冲读取器中,最后看起来像这样:

public static void main(String[] args) {

    try {
        File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
        FileReader fr = new FileReader(file);
        BufferedReader bfr = new BufferedReader(fr);

        System.out.println(bfr.readLine());

        bfr.close();

    } catch (IOException e){
        e.printStackTrace();
    }
}


不要忘了在读写后关闭流,也要使用可读的名称(不要做我做过的事,请使用有意义的名称!)

10-07 19:05
查看更多