
正文
JAVA基于File的基本的增删改查
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
直接上代码
public class TestFile { /**
* 创建目录
* @param filename 路径
*/
public static void createFile(String filename) {
File file = new File(filename);
if(!file.exists() && !file.isDirectory()) {
file.mkdir();
}
} /**
* 删除目录
* @param file 文件
* @throws Exception
*/
public static void deleteFile(File file) throws Exception {
if (file.exists()) {//判断文件是否存在
if (file.isFile()) {//判断是否是文件
file.delete();//删除文件
} else if (file.isDirectory()) {//否则如果它是一个目录
File[] files = file.listFiles();//声明目录下所有的文件 files[];
for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件
deleteFile(files[i]);//把每个文件用这个方法进行迭代
}
file.delete();//删除文件夹
}
} else {
System.out.println("所删除的文件不存在");
}
} /**
* 复制文件
* @param oldPath 旧路径
* @param newPath 新路径
* @throws Exception
*/
public static void copyFile(String oldPath,String newPath) throws Exception{
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
File newFile = new File(newPath);
if(!newFile.exists()) {
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
}else {
System.out.println("已存在");
}
} /**
* 更改文件的名字
* @param oldpath旧文件的路径
* @param newName 新名字
*/
public static void changeFileName(String oldpath,String newName) {
File file = new File(oldpath);
String c = file.getParent();
File newPath = new File(c + "/" + newName);
if(newPath.exists()) {
System.out.println("已存在");
}else {
file.renameTo(newPath);
}
}}
亲测有效,有误指出,谢谢!







