3

该程序正在编译,但无法正常工作。它只是处理打开文件异常。请帮助我。谢谢你的时间。

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");
        }
    }
}
4

1 回答 1

1

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

e.printStackTrace()

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

throw new IllegalStateException(e);

或者让 IOException 从 openFile()、printOnScr() 和 main() 中抛出

于 2011-07-16T05:25:25.590 回答