How to work with files in java?

Java provides the File class to create, read, update, and delete files.

Example:


  File myFile = new File("filename.txt");
  

Solution:

Using FileWriter and Scanner to write and read from the file:


  FileWriter writer = new FileWriter(myFile);
  writer.write("Hello, World!");
  writer.close();

  Scanner scanner = new Scanner(myFile);
  while (scanner.hasNextLine()) {
      System.out.println(scanner.nextLine());
  }
  scanner.close();
  

Beginner's Guide to Java