1

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));
1
  • You´re reading from System.in ... so you´re reading not from file but from System input.
    – cljk
    Dec 1, 2013 at 20:42

3 Answers 3

1
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.next();
    scanner.nextLine();

    FileReader file = new FileReader(fileName);

    BufferedReader br = new BufferedReader(FileReader);
1

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)));
5
  • 1
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); Dec 1, 2013 at 20:41
  • I tried this i am getting: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown BufferedReader br = new BufferedReader(new FileReader(fileName));
    – octain
    Dec 1, 2013 at 21:06
  • FileNotFoundException is a checked exception. Dec 1, 2013 at 21:08
  • I handled this, but when I compile it is saying cannot find symbols for filename. what should be in the try block? i have this: try{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(new FileReader(fileName)); }
    – octain
    Dec 1, 2013 at 21:14
  • Ask a different question. There is no meaning of answering your query in comments. This is not a forum. Dec 1, 2013 at 21:15
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.