Using FileInputStream and FileOutputStream classes:
// Reading data from file File file = new File("filename.txt"); try (FileInputStream fis = new FileInputStream(file)) { byte[] data = new byte[(int) file.length()]; fis.read(data); String fileContent = new String(data, "UTF-8"); } // Writing data to file String content = "Hello, world!"; try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(content.getBytes()); }
Using BufferedReader and BufferedWriter classes:
// Reading data from file File file = new File("filename.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } // Writing data to file String content = "Hello, world!"; try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(content); }
Using Scanner class:
// Reading data from file File file = new File("filename.txt"); try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } } // Writing data to file String content = "Hello, world!"; try (PrintWriter writer = new PrintWriter(file)) { writer.print(content); }
Note that these methods throw IOException
in case of any I/O error. Also, it’s important to close the stream after using it to avoid any resource leaks.