- 使用 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("文件不存在");
}
}
}
标签:java,nio,IOException,file,import,public,10.17 From: https://www.cnblogs.com/sword861417845/p/18473273