IO流
1.流
流指的是数据在数据源和程序之间的传输过程,数据源可以是文件、网络、盘等。数据从数据源传入程序(内存),为输入流,是读取的过程;反之为输出流,是写出的过程。
2.文件操作
文件创建
先创建File对象,再调用其方法。
根据文件路径创建;
public File(String pathname)
根据父目录对象创建
public File(File parent, String child)
根据父目录路径创建
public File(String parent, String child)
创建
public boolean createNewFile() throws IOException
3.IO流
分类
按操作的数据单位分为:字节流、字符流
按数据流的方向分为:输入流、输出流
按流的角色分为:节点流、包装流
字节流(8bit) | 字符流 | |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
注:字节流一般用于操作二进制文件,字符流用于操作文本文件。
3.1 字节流
3.1.1 FileInputStream
构造器:
//传参为文件路径
public FileInputStream(String name) throws FileNotFoundException
//传参为文件
public FileInputStream(File file) throws FileNotFoundException
读取方法:
//按字节读取,效率较低,返回值是读取的字节内容
public int read() throws IOException
//按byte数组读取,返回值是读取的字节数,字节内容存放在byte数组中
public int read(byte b[]) throws IOException
public int read(byte b[], int off, int len) throws IOException
3.1.2 FileOutputStream
构造器:
public FileOutputStream(File file) throws FileNotFoundException
//append的值为true为内容追加,否则为内容覆盖
public