如何在Java中读取和写入文件
// 从文件中读取数据 try (Scanner scanner = new Scanner(new File("file.txt"))) { while (scanner.hasNext()) { String data = scanner.next(); // 处理数据 } } catch (FileNotFoundException e) { e.printStackTrace(); } // 向文件中写入数据 try (PrintWriter writer = new PrintWriter(new File("file.txt"))) { writer.println("Hello, World!"); // 写入其他数据 } catch (FileNotFoundException e) { e.printStackTrace(); }