package IO;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/**
* @author 小小小白白白白
*/
public class Create {
public static void main(String[] args) {}
/**
* 创建文件的三种方式
* 1 new File(String pathname) //根据路径构建一个File对象
* 2 new File(File parent,String child) //根据父目录文件+子路径构建
* 3 new File(String parent,String child) //根据父目录+子路径构建
* createNewFile //创建新文件
*/
//方式1
@Test
public void file1(){
//指定文件的创建路径
String filepath = "e:\\new1.txt";
//生成创建对象
File file = new File(filepath);
//调用创建方法
try {
file.createNewFile();
System.out.println("文件1创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
//方式2
public void file2(){
//父目录路径
File parentFile = new File("e:\\");
//子文件名
String filename="new2.txt";
//这里并没有创建文件只是在内存中生成了
File file = new File(parentFile, filename);
try {
//这里才是创建文件将内存中生成的写入磁盘中
file.createNewFile();
System.out.println("文件2创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3
@Test
public void file3(){
String parentPath="e:\\";
String filename="new3.txt";
File file=new File(parentPath,filename);
try {
file.createNewFile();
System.out.println("文件3创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//一些文件方法
@Test
public void info(){
//先创建文件对象
File file = new File("e:\\new1.txt");
//调用相应的方法得到对应信息
//获取文件名
System.out.println("文件名="+file.getName());
//获取文件的绝对路径
System.out.println("绝对路径="+file.getAbsolutePath());
//获取文件的父级目录
System.out.println("父级目录="+file.getParent());
//获取文件的字节大小
System.out.println("字节大小="+file.length());
//文件是否存在
System.out.println("文件是否存在="+file.exists());
//是否是一个文件
System.out.println("是否是一个文件"+file.isFile());
//是否是一个目录
System.out.println("是否是一个目录="+file.isDirectory());
}
//对文件(目录)进行操作
@Test
public void delete(){
String filepath = "e:\\new1.txt";
//在Java中目录也可以被当做文件进行操作
String filepath1 = "e:\\111";
//对多级目录进行操作
String filepath2 = "e:\\Test\\a\\b\\c";
File file = new File(filepath1);
File file1 = new File(filepath2);
if(file.exists()){
if(file.delete()){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}else {
System.out.println("文件不存在");
}
if(file1.exists()){
System.out.println("目录存在");
}else {
//这里如果是mkdirs就是能创建多级目录,如果是mkdir则只能创建一个目录
if(file1.mkdirs()){
System.out.println("创建成功");
}else {
System.out.println("创建失败");
}
}
}
}