Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
        }
    }
}
like image 820
rj45 Avatar asked Feb 15 '26 00:02

rj45


1 Answers

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()

like image 149
Ryan Stewart Avatar answered Feb 17 '26 14:02

Ryan Stewart