在Java中,可以使用java.util
包中的類來處理文件的輸入輸出(I/O)操作。以下是一些常用的方法和類:
java.util.Scanner
類讀取文件內容:import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
File file = new File("path/to/your/file.txt");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
java.util.BufferedReader
類讀取文件內容:import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File("path/to/your/file.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
java.util.PrintWriter
類寫入文件內容:import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteFile {
public static void main(String[] args) {
File file = new File("path/to/your/outputfile.txt");
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Hello, World!");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
這些示例展示了如何使用Java的java.util
包中的類來讀取和寫入文件。注意,這些示例使用了try-with-resources語句,這是一種自動關閉資源(如文件)的現代方法,可以避免資源泄漏。