Unable to open file in JAVA


I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code

 public static void main(String[] args) {


    try 
    {

       BufferedReader reader = new BufferedReader(new FileReader("test.txt"));

       String line = null;
        while ((reader.readLine()!= null))  
        {
            line = reader.readLine();
            System.out.println(line);
        }   
       reader.close();          
    }
    catch(Exception ex) 
    {
        System.out.println("Unable to open file ");             
    }

}

It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.


Answers:


If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:

final Path path = FileSystems.getDefault().getPath("test.txt");  // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    String line = null;        
    while ((line = r.readLine()) != null) {
        System.out.println(line);
    }
}  // No need for catch; let IOExceptions bubble up.
   // No need for finally; try-with-resources auto-closes.

You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.