【问题标题】:Java text file reading program with bufferedreader and FileReader. Compiling But not working带有bufferedreader和FileReader的Java文本文件读取程序。编译但不工作
【发布时间】:2011-10-06 14:55:17
【问题描述】:

该程序正在编译,但无法运行。它只是处理打开文件异常。请帮助我。感谢您的宝贵时间。

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

【问题讨论】:

  • 你忘记添加你得到的异常的堆栈跟踪。
  • 为什么你认为抛出 IOException 意味着文件不存在?你在 e 中看到了什么信息?

标签: java bufferedreader filereader


【解决方案1】:

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

打印出来
e.printStackTrace()

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

throw new IllegalStateException(e);

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

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2018-08-04
    • 2014-05-09
    • 2023-03-27
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2017-03-20
    相关资源
    最近更新 更多