- 使用 java.io 包進行檔案操作
檔案寫入
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, World!");
System.out.println("檔案寫入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
檔案讀取
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用 java.nio 包進行檔案操作
檔案寫入
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class NIOFileWriteExample {
public static void main(String[] args) {
Path path = Paths.get("example_nio.txt");
String content = "Hello, NIO World!";
try {
Files.write(path, content.getBytes());
System.out.println("檔案寫入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
檔案讀取
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class NIOFileReadExample {
public static void main(String[] args) {
Path path = Paths.get("example_nio.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 檔案刪除
使用 java.nio.file 進行檔案刪除:
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class FileDeleteExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
Files.deleteIfExists(path);
System.out.println("檔案已刪除");
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 檔案和目錄檢查
使用 Files 類來檢查檔案或目錄是否存在:
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileCheckExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
if (Files.exists(path)) {
System.out.println("檔案存在");
} else {
System.out.println("檔案不存在");
}
}
}