使用bufferedreader和FileReader的Java文本文件读取程序。编译但不工作

时间:2011-07-16 04:45:26

标签: java bufferedreader filereader

此程序正在编译但不起作用。它只是处理打开文件异常。请帮助我。谢谢你的时间。

import java.io.*;
import java.util.Scanner;

public class ReadingFile {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ReadingFile rf = new ReadingFile();
        rf.printOnScr();
    }

    private BufferedReader openFile(String meString){
        Scanner sc = new Scanner(System.in);
        BufferedReader bf = null;
        while (bf == null) {
            try {
                System.out.println("Enter a file name");
                String fileName = sc.nextLine();

                FileReader b = new FileReader(fileName);

                bf = new BufferedReader(b);

            } catch (IOException e) {
                System.out.println("The file you are trying to open dose not exist.");
            }   
        }
        return bf;
    }
    private void printOnScr() {
        BufferedReader br = openFile("Please enter a file");
        try {
            while(true){
                String  line = br.readLine();
                if(line == null) break;
                System.out.println(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println("The line you are trying to access have problem/s");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

很可能在键入文件时没有指定文件的正确路径。它应该是绝对路径或基于当前工作目录的相对路径。但是,要确切了解发生了什么,您需要查看引发的异常。用

打印出来
e.printStackTrace()

或将其包装在未经检查的异常中:

throw new IllegalStateException(e);

或者从openFile(),printOnScr()和main()

中抛出IOException