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));
octain
  • 874
  • 2
  • 9
  • 22
  • You´re reading from System.in ... so you´re reading not from file but from System input. – cljk Dec 01 '13 at 20:42

3 Answers3

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)));
Community
  • 1
  • 1
Anirban Nag 'tintinmj'
  • 4,897
  • 3
  • 26
  • 47
  • 1
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); – user1009569 Dec 01 '13 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 01 '13 at 21:06
  • `FileNotFoundException` is a [checked exception](http://stackoverflow.com/questions/3747155/why-am-i-getting-must-be-caught-or-declared-to-be-thrown-on-my-program). – Anirban Nag 'tintinmj' Dec 01 '13 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 01 '13 at 21:14
  • Ask a different question. There is no meaning of answering your query in comments. This is not a forum. – Anirban Nag 'tintinmj' Dec 01 '13 at 21:15
1
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.next();
    scanner.nextLine();

    FileReader file = new FileReader(fileName);

    BufferedReader br = new BufferedReader(FileReader);
openmike
  • 272
  • 1
  • 9
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.

user1009569
  • 447
  • 6
  • 21