对文件夹的增加
对文件的增加
对文件的删除
代码演示:
package com.example.io;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class FileTest {
public static void main(String[] args) {
// 得到文件路径
FileTest fileTest = new FileTest();
String path = fileTest.getFilePath();
path = getPath(path);
// 得到这样的路径: D:\IDEAALL2\dtest\target\classes\com\example\io\
System.out.println(path);
// 文件夹的创建
// 先添加一个以前没有的文件夹
path = path+"testFile01";
System.out.println(path);
// 得到路径后就可以创建文件夹了:(创建文件夹时,不能有多余的文件,可能会创建失败)
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
// 文件的创建
path = path + "\\123.txt";
file = new File(path);
if(!(file.exists())){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("文件名称:" + file.getName());
System.out.println("文件是否存在:" + file.exists());
System.out.println("文件的相对路径:" + file.getPath());
System.out.println("文件的绝对路径:" + file.getAbsolutePath());
System.out.println("是否为可执行文件:" + file.canExecute());
System.out.println("文件可以读取:" + file.canRead());
System.out.println("文件可以写入:" + file.canWrite());
System.out.println("文件上级路径:" + file.getParent());
System.out.println("文件大小:" + file.length() + "B");
System.out.println("文件最后修改时间:" + new Date(file.lastModified()));
System.out.println("是否文件类型:" + file.isFile());
System.out.println("是否为文件夹:" + file.isDirectory());
// 文件的删除
if(!file.exists()){
System.out.println("文件不存在!");
}
boolean isSuccess = file.delete();
if(isSuccess){
System.out.println("文件删除成功!");
}else {
System.out.println("文件删除失败!");
}
}
public String getFilePath(){
return this.getClass().getResource("").getPath();
}
public static String getPath(String pathIn){
pathIn = pathIn.substring(1,pathIn.length());
pathIn = pathIn.replace("/", "\\");
System.out.println("pathIn==="+pathIn);
return pathIn;
}
}