在Ubuntu下使用Java進行文件操作,主要依賴于Java的I/O庫。以下是一些常用的文件操作方法:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
File file = new File("/path/to/your/file.txt");
// 創建文件
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 創建目錄
File directory = new File("/path/to/your/directory");
if (!directory.exists()) {
directory.mkdirs();
}
// 刪除文件
if (file.exists()) {
file.delete();
}
// 刪除目錄
if (directory.exists()) {
directory.delete();
}
try {
List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
String content = "Hello, World!";
Files.write(Paths.get(file.getAbsolutePath()), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
try {
String content = "\nAppended content";
Files.write(Paths.get(file.getAbsolutePath()), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
try {
Files.copy(Paths.get("/path/to/source/file.txt"), Paths.get("/path/to/destination/file.txt"));
} catch (IOException e) {
e.printStackTrace();
}
try {
Files.move(Paths.get("/path/to/source/file.txt"), Paths.get("/path/to/destination/file.txt"));
} catch (IOException e) {
e.printStackTrace();
}
這些示例展示了如何在Ubuntu下使用Java進行基本的文件操作。你可以根據需要組合這些方法來實現更復雜的文件操作。