S09-01 IO-File
[TOC]
文件
什么是文件
- 保存数据的载体(如文档、图片、视频等)
文件流
- 流:数据在程序(内存)和文件(磁盘)之间的传输路径
- 输入流:数据从文件到程序(读操作)
- 输出流:数据从程序到文件(写操作)
常用的文件操作
创建文件对象的三种方式
java
package com.hspedu.file;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/**
* 演示创建文件
* @author 韩顺平
* @version 1.0
*/
public class FileCreate {
// 方式1:new File(String pathname)
@Test
public void create01() {
String filePath = "e:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
// 方式2:new File(File parent, String child)
@Test
public void create02() {
File parentFile = new File("e:\\");
String fileName = "news2.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
// 方式3:new File(String parent, String child)
@Test
public void create03() {
String parentPath = "e:\\";
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
}获取文件相关信息
java
package com.hspedu.file;
import org.junit.jupiter.api.Test;
import java.io.File;
/**
* 获取文件信息
* @author 韩顺平
* @version 1.0
*/
public class FileInformation {
@Test
public void info() {
File file = new File("e:\\news1.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());
}
}目录操作和文件删除
| 方法 | 功能 |
|---|---|
mkdir() | 创建一级目录 |
mkdirs() | 创建多级目录 |
delete() | 删除空目录或文件 |