rj45
rj45

Reputation: 31

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

Upvotes: 3

Views: 3113

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128919

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

Upvotes: 1

Related Questions