文件对象
构建File
对象
import java.io.*;
public class Main {
public static void main(String[] args){
// 绝对路径
File f = new File("D:\\java\\Program.exe");
// 相对路径 当前路径为D:\java
File f = new File(".\\Program.exe");
}
}
File
常用方法
File
对象可以返回路径
f.getPath(); // 返回构造时传入的路径
f.getAbsolutePath(); // 返回绝对路径
f.getCanonicalPath(); // 返回规范路径
File
对象可以给出当前系统的分隔符
f.separator(); // Windows: '\'; Ubuntu: '/'
判断File
是否是一个已存在的文件/目录
f.isFile();
f.isDirectory();
创建/删除文件
f.createNewFile("FileNmae", ".txt");
f.delete();
f.createTempFile("FileNmae", ".txt"); // 创建临时文件
f.deleteOnExit(); // 在JVM退出时自动删除临时文件;
遍历文件/目录
File[] fs = f.listFiles();
for (File f : fs){
System.out.println(f);
}
Path
对象
public class Main {
public static void main(String[] args) throws IOException {
Path p1 = Paths.get(".", "project", "study"); // 构造一个Path对象
System.out.println(p1);
Path p2 = p1.toAbsolutePath(); // 转换为绝对路径
System.out.println(p2);
Path p3 = p2.normalize(); // 转换为规范路径
System.out.println(p3);
File f = p3.toFile(); // 转换为File对象
System.out.println(f);
for (Path p : Paths.get("..").toAbsolutePath()) { // 可以直接遍历Path,..为上一层目录
System.out.println(" " + p);
}
}
文件读写
读写
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String path = "./test.txt";
String content = "你好,再见";
// File f1 = new File("./src/test.txt");
// if (f1 == null) {f1.createNewFile();}
writeFile(path, content);
System.out.println(readFile(path));
}
public static String readFile(String path) throws IOException {
try(InputStream input = new FileInputStream(path)) {
byte[] buffer = new byte[1024];
int n;
StringBuilder sb = new StringBuilder();
while ((n = input.read(buffer)) != -1) {
sb.append(new String(buffer, "UTF-8"));
}
return sb.toString();
}
}
public static void writeFile(String path, String content) throws IOException {
try(OutputStream output = new FileOutputStream(path)){
output.write(content.getBytes("UTF-8"));
output.flush();
}
}
}
复制文件
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFile {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage:\n java CopyFile.java <source> <target>");
System.exit(1);
}
copy(args[0], args[1]);
System.out.println("Done !");
}
static void copy(String source, String target) throws IOException {
try (InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(target))
{
byte[] buffer = new byte[1024];
int n;
String s;
StringBuilder sb = new StringBuilder();
while ((n = input.read(buffer)) != -1) {
sb.append(new String(buffer, "UTF-8" ));
}
s = sb.toString();
output.write(s.getBytes("UTF-8"));
}
}
}