Read from a file using java.

How do i read from a file (the test cases) and output the results into a file using java. Are there any standard functions?

1 Like

You can use Scanner or BufferedReader just like you would read from standard I/O.

    try 
    {
       Scanner in = new Scanner(new File("filename.txt"));
    }
    catch (FileNotFoundException e)
    {
       // Handle file not found case
    }

To print to a file us PrintWriter in a similar manner.

there are a lot of functions that you can use to read a File from a java file.

  FileInputStream fstream = null;
  try {
  fstream = new FileInputStream("c:\\hello.txt");
// Decode data using UTF-8
  BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
   String strLine;
// Read File Line By Line
  while ((strLine = br.readLine()) != null) {
    // Print the content on the console
    System.out.println(strLine);
    }
 } catch (Exception e) {// Catch exception if any
  System.err.println("Error: " + e.getMessage());
  } finally {
   if (fstream != null) {
    try { fstream.close(); }
    catch (IOException e) {
        // log failure to close file
      }
   }

}