1. java.io.File
- File不是一个流,通过File不能完成文件的读写。
- File是文件和目录路径名的抽象表示形式。
- File类中常用的方法:
Step 1:使用构造方法创建File对象
File f1 = new File("D:\\file")
Step 2: 判断"D:\file"是否存在,如果不存在,则以文件的形式创建出来
if(!f1.exists()){
f1.createNewFile();
}
或者:以目录的形式创建
f1.mkdir();
或者:以多重目录的形式创建
File f2 = new File("D:/a/b/c/d");
f2.mkdirs();
获取当前文件的父路径:
String parentPath = f2.getParent();
//获取绝对路径
File parentFile = f2.getParentFile();
parentFile.getAbsolutePath();//获取绝对路径
其他常用方法
2. 目录拷贝
import java.io.*;
public class CopyAllTest01 {
/*
拷贝目录
*/
public static void main(String[] args) {
//拷贝源
File srcFile = new File("C:\\Users\\yangx\\Desktop\\papers");
//拷贝目标
File destFile = new File("C:\\");
//调用拷贝方法
copyDir(srcFile, destFile);
}
/**
*
* @param srcFile 拷贝源
* @param destFile 拷贝目标
*/
private static void copyDir(File srcFile, File destFile) {
if(srcFile.isFile()){
//是文件的时候需要拷贝,一边读,一边写
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
out = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\" )+ srcFile.getAbsolutePath().substring(3));
byte[] bytes = new byte[1024 * 1024];
int readCount = 0;
while ((readCount = in.read(bytes)) != -1){
out.write(bytes,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;//如果srcFile是一个文件的话,递归结束
}
// 获取源下面的子目录
File[] files = srcFile.listFiles();
for(File file: files){
//获取所有文件的绝对路径
String srcDir = file.getAbsolutePath();
String dstDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\" )+ srcDir.substring(3);
// System.out.println(file.getAbsolutePath());
// if(file.isDirectory()){
// //新建对应目录
// String srcDir = file.getAbsolutePath();
// String dstDir =destFile.getAbsolutePath() + srcDir.substring(3);
// System.out.println(dstDir);
// }
//file可能是文件,也可能是目录,但是是一个file对象
copyDir(file,destFile);
}
}
}