如何打开文本文件?

我无法弄清楚这个程序有什么问题:

import java.io.*; public class EncyptionAssignment { public static void main (String[] args) throws IOException { String line; BufferedReader in; in = new BufferedReader(new FileReader("notepad encypt.me.txt")); line = in.readLine(); while(line != null) { System.out.println(line); line = in.readLine(); } System.out.println(line); } } 

错误消息说无法找到该文件,但我知道该文件已存在。 我是否需要将文件保存在特殊文件夹中?

错误是"notepad encypt.me.txt" 。 由于您的文件名为“encypt.me.txt”,因此您无法在其名称前加上“记事本”。 此外,名为“notepad encypt.me.txt”的文件可能不存在或者不是您要打开的文件。

此外,如果文件不在项目文件夹中,则必须提供文件的路径(绝对路径或相对路径)。

我将假设您使用的是Microsoft Windows系统。

如果您的文件具有“C:\ foo \ bar \ encypt.me.txt”的绝对路径,则必须将其作为"C:\\foo\\bar\\encypt.me.txt""C:"+File.separatorChar+"foo"+File.separatorChar+"bar"+File.separatorChar+encypt.me.txt"

如果它仍然不起作用,您应该validation该文件:

1)存在于提供的路径上。 您可以使用以下代码来完成:

 File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt"); System.out.println(encyptFile.exists()); 

如果提供的路径是正确的,那么它应该是真的。

2)可以由应用程序读取

您可以使用以下代码来完成:

 File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt"); System.out.println(encyptFile.canRead()); 

如果您有权读取该文件,则应该为true。

更多信息:

文件的Javadoc

在计算机中的路径信息

 import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; // This will reference one line at a time String line = null; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } // Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } } 
 package com.mkyong.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("C:\\testing.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } 

参考: http : //www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/