简体   繁体   English

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

[英]Java text file reading program with bufferedreader and FileReader. Compiling But not working

This program is compiling though not working.该程序正在编译,但无法正常工作。 It just handling the opening file exception.它只是处理打开文件异常。 Please help me.Thanks for your time.请帮助我。谢谢你的时间。

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

Very probably you're not specifying the correct path to the file when you type it.很可能您在键入文件时没有指定正确的文件路径。 It should either be an absolute path or a relative path based at your current working directory.它应该是基于当前工作目录的绝对路径或相对路径。 To see exactly what's happening, though, you'll need to look at the exception that's thrown.但是,要确切了解发生了什么,您需要查看引发的异常。 Either print it out with要么打印出来

e.printStackTrace()

or wrap it in an unchecked exception:或将其包装在未经检查的异常中:

throw new IllegalStateException(e);

or let IOException be thrown from openFile(), through printOnScr(), and out of main()或者让 IOException 从 openFile()、printOnScr() 和 main() 中抛出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM