1.什么是文件
文件是保存数据的地方,比如大家经常使用的word文档、txt文件、excel文件等等都是文件。它即可以保存一张图片,也可以保存视频、声音···
2.文件流概念
文件在程序中是以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经历的路径;
输入流:数据从数据源(文件)到程序(内存)的路径;
输出流:数据从程序(内存)到数据源(文件)的路径。
3.常用的文件操作
1.创建文件对象相关构造器和方法
//根据路径构建一个File对象
new File(String pathname);
//根据父目录文件+子路径构建
new File(File parent,String child);
//根据父目录+子路径构建
new File(String parent,String child);
代码:
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/**
* @author zhangwenhui
* @version 1.0
*/
public class FileCreate {
//1.根据路径构建一个File对象
@Test
public void createFile01(){
String filePath = "d:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
//2.根据父目录文件+子路径构建
@Test
public void createFile02(){
//在内存里创建file对象
File parentFile = new File("d:\\");
String fileName = "news2.txt";
File file = new File(parentFile,fileName);
try {
//真正在磁盘创建文件
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//3.根据父目录+子路径构建
@Test
public void createFile03(){
String parentFile = "d:\\";
String fileName = "news3.txt";
File file = new File(parentFile,fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.获取文件的相关信息
获取到文件的大小、文件名、路径、父File,是文件还是目录(目录本质也是文件,一种特殊的文件)是否存在。
String parentFile = "d:\\";
String fileName = "news3.txt";
File file = new File(parentFile,fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//常用方法,获取file对象信息
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());
3.目录的操作和文件删除
- mkdir 创建一级目录
- mkdirs 创建多级目录
- delete 删除空目录或文件
判断文件是否存在以及删除
String parentFile = "d:\\";
String fileName = "news3.txt";
File file = new File(parentFile,fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//判断文件是否存在
if(file.exists()){
//删除文件
if(file.delete()){
System.out.println("删除成功");
}
}else{
System.out.println("该文件不存在");
}
//判断目录是否存在以及创建目录
String parentFile = "d:\\demo\\a\\b\\c";
File file = new File(parentFile);
if(file.exists()){
System.out.println("目录存在");
}else{
if(file.mkdirs()){
System.out.println("创建成功");
}else{
System.out.println("创建是吧");
}
}