Java 流概述

文件通常是由一连串的字节或字符构成,组成文件的字节序列称为字节流,组成文件的字符序列称为字符流。Java 中根据流的方向可以分为输入流和输出流。输入流是将文件或其它输入设备的数据加载到内存的过程;输出流恰恰相反,是将内存中的数据保存到文件或其他输出设 备

  • 流:数据在数据源文件和程序内存直接经历的路径
  • 输入流:数据从数据源文件到程序内存的路径
  • 输出流:数据从程序内存到数据源文件的路径

常用文件操作

创建文件方法

  • new File(String pathname) :根据路径构建一个File对象
  • new File(File parent,Sring child):根据父目录文件+子路径构建
  • new File(String parent,String child):根据父目录+子路径构建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

public class FileCreate {
public static void main(String[] args) {}
//方式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) //根据父目录文件+子路径构建
//e:\\news2.txt
@Test
public void create02() {
File parentFile = new File("e:\\");
String fileName = "news2.txt";
//这里的file对象,在java程序中,只是一个对象,创建在内存中
//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
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 = "news4.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
}

获取文件相关信息

  • getName 文件名字
  • getAbsolutePath 文件绝对路径
  • getParent 文件父级目录
  • length 文件大小(字节)
  • exists 文件是否存在
  • isFile 是不是一个文件
  • isDirectory 是不是一个目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public class FileInformation {
public static void main(String[] args) {}

//获取文件的信息
@Test
public void info() {
//先创建文件对象
File file = new File("e:\\news1.txt");
//注意,这里没有用createNewFile方法,因为这并不是在创建文件,而是创建这个已经存在的文件的一个对象,来对这个文件进行一些操作
//调用相应的方法,得到对应信息
System.out.println("文件名字=" + file.getName());
//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());
System.out.println("文件是否存在=" + file.exists());//T
System.out.println("是不是一个文件=" + file.isFile());//T
System.out.println("是不是一个目录=" + file.isDirectory());//F
}
}

目录的操作和文件删除

  • mkdir 创建一级目录
  • mkdirs 创建多级目录
  • delete 删除空目录或文件

流的分类

字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

InputStream

InputStream抽象类式所有类字节输入流的超类

  • FileInputStream:文件输入流
  • BufferedInputStream:缓冲字节输入流
  • ObjectlnputStream:对象字节输入流