Java- Issue with opening and Scanning file

368 views Asked by At

I am writing a program in Java, it scans a file, counts lines, character, palindromes, words. My problem is when I ask for a filename, I am using BufferedReader and InputStreamReader to scan the file the user provided, and print the results in another file, my program compiles, when I type in the name of the file nothing happens, program does not finish, and remains stuck, here is code the BufferedReader, if the entire code is needed i will post it up

System.out.println("Enter the name of the file you would like to scan: ");
                        String fileName = scan.nextLine();

                        File file = new File(fileName);



          BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
3

There are 3 answers

0
user1009569 On

You're creating an InputStreamReader object as System.in as the inputStream property. You'll need to specify a FileInputStream for as the InputStream.

5
Anirban Nag 'tintinmj' On

Try with

BufferedReader br = new BufferedReader(new FileReader(fileName));

actually you are specifying your reader InputStreamReader to read from System as System.in though you are trying to read a file. So you have to use FileReader. See How to read file in Java

also thanks to @user1009560 you can use

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
0
openmike On
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.next();
    scanner.nextLine();

    FileReader file = new FileReader(fileName);

    BufferedReader br = new BufferedReader(FileReader);