java如何访问文件
访问文件的基本方法
Java提供了多种访问文件的方式,主要通过java.io和java.nio包实现。以下是常见的文件操作方法:
使用File类
java.io.File类用于表示文件或目录的路径,可以进行基础操作:
File file = new File("path/to/file.txt");
boolean exists = file.exists();
boolean isFile = file.isFile();
long length = file.length();
使用FileInputStream和FileOutputStream
读写二进制文件可以使用字节流:

// 读取文件
try (FileInputStream fis = new FileInputStream("input.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
}
// 写入文件
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write("Hello World".getBytes());
}
使用BufferedReader和BufferedWriter
处理文本文件时,字符流更高效:
// 读取文本文件
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
// 写入文本文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello World");
bw.newLine();
}
使用Files类(NIO)
Java NIO的Files类提供了更简洁的API:

// 读取所有行
List<String> lines = Files.readAllLines(Paths.get("input.txt"));
// 写入文件
Files.write(Paths.get("output.txt"), "Hello World".getBytes());
// 复制文件
Files.copy(Paths.get("source.txt"), Paths.get("dest.txt"));
处理文件路径
使用Paths和Path类处理路径更安全:
Path path = Paths.get("folder", "subfolder", "file.txt");
Path absolutePath = path.toAbsolutePath();
Path normalizedPath = path.normalize();
异常处理
文件操作必须处理IOException:
try {
Files.readAllLines(Paths.get("file.txt"));
} catch (IOException e) {
e.printStackTrace();
}
临时文件创建
创建临时文件的方法:
Path tempFile = Files.createTempFile("prefix", ".suffix");
System.out.println("Temp file: " + tempFile);
以上方法涵盖了Java中文件操作的主要场景,根据需求选择适合的方式。NIO包提供的方法通常更现代且功能更强大,适合新项目使用。






