java如何放指定文件
读取指定文件
使用 FileInputStream 或 BufferedReader 读取文件内容。FileInputStream 适用于二进制文件,BufferedReader 适用于文本文件。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
写入指定文件
使用 FileOutputStream 或 BufferedWriter 写入文件内容。FileOutputStream 适用于二进制文件,BufferedWriter 适用于文本文件。
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
bw.write("Hello, World!");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
检查文件是否存在
使用 File 类的 exists() 方法检查文件是否存在。
import java.io.File;
public class CheckFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
File file = new File(filePath);
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}
创建目录
使用 File 类的 mkdir() 或 mkdirs() 方法创建目录。mkdir() 创建单层目录,mkdirs() 创建多层目录。
import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
String dirPath = "path/to/your/directory";
File dir = new File(dirPath);
if (dir.mkdirs()) {
System.out.println("Directory created.");
} else {
System.out.println("Directory already exists.");
}
}
}
删除文件
使用 File 类的 delete() 方法删除文件。
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
File file = new File(filePath);
if (file.delete()) {
System.out.println("File deleted.");
} else {
System.out.println("File does not exist or could not be deleted.");
}
}
}
使用 NIO 文件操作
Java NIO 提供了 Files 和 Paths 类,简化文件操作。

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class NIOFileOperations {
public static void main(String[] args) throws IOException {
String filePath = "path/to/your/file.txt";
List<String> lines = Files.readAllLines(Paths.get(filePath));
lines.forEach(System.out::println);
Files.write(Paths.get(filePath), "New content".getBytes(), StandardOpenOption.WRITE);
}
}






