package java3;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* File类的使用
*
* 1.File类的对象代表一个文件或者一个文件目录(俗称文件夹)
* 2.File声明在java.io包下
* 3.File(String FilePath);
* File(String parentPath,String childPath)
* File(File parentFile,String childPath)
* @author Baobao
* @create 2021-08-19 22:29
*/
public class FileTest {
/*
1.如何创建File类实例
2.相对路径:相较于某个路径下指明的路径
绝对路径:包含盘符在内的路径或者文件目录的路径
3.file类中涉及文件or文件目录的创建,删除,重命名,修改时间,文件大小等方法
并未涉及写入或者读取文件内容的操作,如果需要读写文件内容,就需要IO流
4.后续File类的对象常常作为参数传入IO流的构造器中,作为读写的终点
*/
@Test
public void test01(){
File file1=new File("hello.txt");
System.out.println(file1);
}
@Test
public void test02(){
File file1=new File("hello.txt");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParentFile());
System.out.println(file1.length());
System.out.println(file1.lastModified());
System.out.println();
}
/*
public boolean renameTo (File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例
要想返回True,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
*/
@Test
public void test03(){
}
/*
public boolean isDirectory();//判断是否是文件目录
public boolean isFile():判断是否是文件
public boolean exists():判断是否存在
public boolean canRead():判断是否可读
public boolean canWrite():判断是否可写
public boolean isHidden():判断是否可写
*/
@Test
public void test04(){
File file1=new File("hello.txt");
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file1.isFile());
System.out.println(file1.isDirectory());
}
/*
创建文件对应的功能
*/
@Test
public void test05() throws IOException {
File file1=new File("hi.txt");
if(!file1.exists()){
file1.createNewFile();
System.out.println("创建成功!");
}else{
file1.delete();//要想删除成功,路径下不能有文件或者是子目录,需要遍历去删除。
System.out.println("删除成功");
}
}
@Test
public void test06(){
File file1=new File("D:\\JJJJJ\\body");
boolean mkdir = file1.mkdir();
if(mkdir){
System.out.println("创建成功");
}
/*
如果当前文件目录的上层目录不存在,mkdirs可以帮忙创建,而mkdir不会。
*/
}
}
【Java-14】关于文件
最新推荐文章于 2023-07-06 10:07:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)