Java知识点--IO流(上)
一、文件
1、文件的含义
文件是保存数据的地方,比如word文档,txt文本文件,视频,图片等都是文件。
2、文件流
文件在程序中是以流的形式来操作的。
输入流:数据从文件到程序(内存)的路径。(在程序中读取文件数据)
输出流:数据从程序(内存)到文件的路径。(在程序中将数据写入文件)
二、常用的文件操作
1、创建文件对象相关构造器和方法
相关构造器:
new File(String filePath) 根据路径创建File对象
new File(File parent,String child) 根据父目录文件+子路径创建File对象
new File(tring parent,String child) 根据父目录+子路径创建File对象
方法:
createNewFile 创建新文件
2、创建文件案例演示(三种创建方法)
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
public class FileCreate {
public static void main(String[] args) {
}
@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();
}
}
@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();
}
}
@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();
}
}
}
3、获取文件相关信息的方法
“文件名字” — getName()
“文件绝对路径” — getAbsolutePath()
“文件父级目录” — getParent()
“文件大小(字节)” — length()
“文件是否存在” — exists()
“是不是一个文件” — isFile()
“是不是一个目录” — isDirectory()
4、获取文件相关信息方法案例演示
import org.junit.jupiter.api.Test;
import java.io.File;
public class FileInformation {
public static void main(String[] args) {
}
@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