无法读取程序中的Java文件

时间:2016-10-12 20:22:12

标签: java hashmap try-catch bufferedreader filereader

我创建了一个Java程序,它读取文件并在输出中显示相同的内容。但我的输出就像无法打开文件test.txt。有什么帮助吗?

package test;
import java.io.*;

public class Test {

    public static void main(String[] args) {
        // The name of the file to open.
        String fileName = "test.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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试将"整体"文件的路径,而不仅仅是名称。就像"用户/.../.../ test.txt"。

希望它有所帮助。