Java——IO
文件概念
文件流:文件在程序中是以流的形式来操作的。

流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
常用的文件操作
创建文件对象相关构造器和方法:
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
| 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("文件1创建成功!"); } catch (IOException e) { throw new RuntimeException(e); } }
@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("文件2创建成功!"); } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void create03(){ String parentPath = "E:\\"; String filePath = "news3.txt"; File file = new File(parentPath, filePath); try { file.createNewFile(); System.out.println("文件3创建成功!"); } catch (IOException e) {
} } }
|
获取文件的相关信息:
1 2 3 4 5 6 7 8 9 10
| 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()); }
|
目录的操作和文件删除:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public void m1(){ String filePath = "E:\\news1.txt"; File file = new File(filePath); if (file.exists()){ if(file.delete()){ System.out.println("删除成功.."); }else { System.out.println("删除失败.."); } }else { System.out.println("该文件不存在...."); } } public void m2(){ String directoryPath = "F:\\demo\\a\\b\\c"; File file = new File(directoryPath); if (file.exists()){ System.out.println(directoryPath + "已存在.."); }else { file.mkdirs(); } }
|
mkdir()创建一级目录,mkdirs()创建多级目录,delete删除空目录或文件
Java IO流原理
- I/O是 Input/Output 的缩写,I/O技术是非常实用的技术,用于处理数据传输,如读/写文件,网络通信等
- Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行
- Java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
流的分类
按操作数据单位不同分为:字节流(8bit)二进制文件(图片,视频,音频),字符流(按字符)文本文件
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流/包装流
| (抽象基类) |
字节流 |
字符流 |
| 输入流 |
InputStream |
Reader |
| 输出流 |
OutputStream |
Writer |
- Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的
- 由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀
- FileInputStream:文件输入流
- BufferedInputStream:缓冲字节输入流
- ObjectInputStream:对象字节输入流
读取文件中单个字符:fileInputStream.read()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public void readFile01(){ FileInputStream fileInputStream = null; String filePath = "F:\\Hello.txt"; int readData = 0; try { fileInputStream = new FileInputStream(filePath); while((readData = fileInputStream.read())!=-1){ System.out.print((char)readData); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
|
读取文件中多个字符:fileInputStream.read(new byte[n])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public void readFile02(){ FileInputStream fileInputStream = null; String filePath = "F:\\Hello.txt"; byte[] buf = new byte[12]; int readLen; try { fileInputStream = new FileInputStream(filePath); while((readLen = fileInputStream.read(buf))!=-1){ System.out.print(new String(buf,0,readLen)); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
|
FileOutputStream
public FileOutputStream(File file)
public FileOutputStream(File file,boolean append)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public void writeFile01(){ FileOutputStream fileOutputStream = null; String filePath = "F:\\fileOutputStream.txt"; String str = "Hello,world!"; try { fileOutputStream = new FileOutputStream(filePath); fileOutputStream.write(str.getBytes(),0,5); } catch (IOException e) { throw new RuntimeException(e); } finally { try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
|
文件copy
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
| public class FileCopy { public static void main(String[] args) { String scrFilePath = "F:\\jietu.png"; String destFilePath = "E:\\aaa.png";
FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; byte[] buf = new byte[1024]; int readLen; try { fileInputStream = new FileInputStream(scrFilePath); fileOutputStream = new FileOutputStream(destFilePath); while((readLen = fileInputStream.read(buf))!=-1){ fileOutputStream.write(buf,0,readLen); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } System.out.println("copy over!"); } } }
|
FileReader

相关方法:
- new FileReader(File/String)
- read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
- read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1
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
| @Test public void readFile01(){ FileReader fileReader = null; String filePath = "E:\\javaIO\\readerTest.txt"; int data; try { fileReader = new FileReader(filePath); while((data = fileReader.read())!=-1){ System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
@Test public void readFile02(){ FileReader fileReader = null; String filePath = "E:\\javaIO\\readerTest.txt"; int readLen; char[] ch = new char[1024]; try { fileReader = new FileReader(filePath); while((readLen = fileReader.read(ch))!=-1){ System.out.print(new String(ch,0,readLen)); } } catch (IOException e) { e.printStackTrace(); } finally { try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
|
FileWriter

相关方法:
- new FileWriter(File/String):覆盖模式,相当于流的指针在首端
- new FileWriter(File/String):追加模式,相当于流的指针在末尾
- write(int):写入单个字符
- write(char[]):写入指定数组
- write(char[],off,len):写入指定数组的指定部分
- write(string):写入整个字符串
- write(string,off,len):写入字符串的指定部分
- 相关API:String类:toCharArray:将String转换成char[]
【注意】:FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Test public void fileWrite01(){ String filePath = "E:\\javaIO\\fileWriteTest.txt"; FileWriter fileWriter = null; try { fileWriter = new FileWriter(filePath); fileWriter.write("h"); fileWriter.write("刘亦菲"); fileWriter.write("女"); fileWriter.write("风雨之后,定见彩虹".toCharArray()); fileWriter.write("风雨之后,定见彩虹",1,6);
} catch (IOException e) { throw new RuntimeException(e); } finally { try { fileWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
|
节点流和处理流
- 节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter
- 处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedReader、BufferedWriter

区别和联系:
- 节点流是底层流/低级流,直接跟数据源相接
- 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法完成输入输出
- 处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
处理流的功能主要体现在以下两个方面:
- 性能的提高:主要以增加缓冲的方式来提高输入输出的效率
- 操作的边界:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便
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
| import java.io.*;
public class BufferedCopy { public static void main(String[] args) {
String srcFilePath = "F:\\javaIO\\aaa.png"; String destFilePath = "F:\\javaIO\\aaa2.png";
BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null;
byte [] buf = new byte[1024]; int len; try { bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFilePath)); bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFilePath)); while ((len = bufferedInputStream.read(buf))!=-1){ bufferedOutputStream.write(buf,0,len); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { bufferedInputStream.close(); bufferedOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
|
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
| import java.io.*;
public class BufferedCopy { public static void main(String[] args) { String srcFilePath = "F:\\javaIO\\readerTest.txt"; String destFilePath = "F:\\javaIO\\readerTest2.txt"; BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; String line; try { bufferedReader = new BufferedReader(new FileReader(srcFilePath)); bufferedWriter = new BufferedWriter(new FileWriter(destFilePath)); while ((line = bufferedReader.readLine())!=null){ bufferedWriter.write(line); bufferedWriter.newLine(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
|
对象流
需求:能够将 基本数据类型 或者 对象 进行 序列化 和反序列化操作
- 序列化:在保存数据时,保存数据的值和数据类型
- 反序列化:在恢复数据时,恢复数据的值和数据类型
- 需要让某个对象支持序列化机制,则必须让其类是可系列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
- Serializable //这是一个标记接口,没有方法 (首选)
- Externalizable //该接口有方法需要实现
- ObjectOutputStream 提供序列化功能
- ObjectInputStream 提供反序列化功能
注意事项与细节:
- 读写顺序要一致
- 要求实现序列化或反序列化,需要实现 Serializable
- 序列化的类中建议添加 SerialVersionUID(序列化的版本号),为了提高版本的兼容性
- 序列化对象时,默认将里面所有的属性都进行序列化,但除了static和transient(使其被标记的成员不会被序列化)修饰的成员
- 序列化对象时,要求里面的属性类型也需要实现序列化接口
- 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.mhl.outputstream;
import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream;
public class ObjectOutputStream_ { public static void main(String[] args) throws IOException {
String filePath = "F:\\javaIO\\data.dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath)); oos.writeInt(100); oos.writeBoolean(true); oos.writeChar('a'); oos.writeDouble(9.5); oos.writeUTF("韩顺平"); oos.writeObject(new Dog("小黄",5));
oos.close(); System.out.println("数据保存完毕"); } }
|
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
| package com.mhl.inputstream;
import com.mhl.outputstream.Dog;
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream;
public class ObjectInputStream_ { public static void main(String[] args) throws IOException, ClassNotFoundException {
String filePath = "F:\\javaIO\\data.dat";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath)); System.out.println(ois.readInt()); System.out.println(ois.readBoolean()); System.out.println(ois.readChar()); System.out.println(ois.readDouble()); System.out.println(ois.readUTF()); Object dog1 = ois.readObject(); System.out.println(dog1); Dog dog = (Dog)dog1; System.out.println(dog.getName());
ois.close(); System.out.println("输出完毕"); } }
|
转换流
InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
OutputStreamWriter:Writer的子类,可以将OutputStream(字节流)包装成Writer(字符流)
当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
可以在使用时指定编码格式(如:UTF-8,GBK等)
public InputStreamReader(InputStream in,Charset cs)
1 2 3 4 5
| 创建一个使用给定字符集的InputStreamReader。
6. ```java public OutputStreamWriter(OutputStream out,Charset cs)
|
创建一个使用给定字符集的OutputStreamWriter。
可以用来解决乱码问题:
test.txt文件编码为默认,直接读取时会出现汉字乱码情况,使用转换流即可解决,先用转换流将字节流包装成字符流,再用包装流Buffered
1 2 3 4 5 6 7 8 9 10 11 12
| public class CodeQuestion { public static void main(String[] args) throws IOException {
String filePath = "F:\\javaIO\\test1.txt"; InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); System.out.println("读取到的内容:" + s); br.close(); } }
|
OutputStreamWrite:
1 2 3 4 5 6 7 8 9 10
| public class OutputStreamWrite_ { public static void main(String[] args) throws IOException {
String filePath = "F:\\javaIO\\test2.txt"; OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8"); osw.write("hello,世界"); osw.close(); System.out.println("保存成功"); } }
|
打印流
PrintStream 和 PrintWrite , 打印流只有输出流,没有输入流
在默认情况下,PrintStream 输出数据的位置是标准输出,即显示器
Print底层使用的是write ,所以可以直接调用write进行打印/输出
可以修改打印流输出的位置/设备
1 2
| System.setOut(new PrintStream("F:\\javaIO\\test3.txt")); System.out.println("hello,世界");
|
这样”hello,世界“将会被写入test3.txt文件中
Properties类
- 专门用于读写配置文件的集合类
- 配置文件的格式: 键=值
- 键值对不需要有空格,值不需要用引号,默认类型是String
Properties的常见方法:
- load :加载配置文件的键值对到Properties对象
- list :将数据显示到指定设备
- getProperty(key):根据键获取值
- setProperty(key,value):设置键值对到Properties对象
- store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
读取:
1 2 3 4 5 6 7 8 9 10 11 12
| public class Properties02 { public static void main(String[] args) throws IOException {
Properties properties = new Properties(); properties.load(new FileReader("src\\mysql.properties")); String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); System.out.println("用户名:" + user); System.out.println("密码:" +pwd); } }
|
创建和修改:
如果该文件没有key,就是创建
如果该文件有key,就是修改
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Properties03 { public static void main(String[] args) throws IOException {
Properties properties = new Properties(); properties.setProperty("charset","utf-8"); properties.setProperty("user","汤姆"); properties.setProperty("pwd","abc111"); properties.setProperty("pwd","999999"); properties.store(new FileOutputStream("src\\mysql02.properties"),"此处为注释"); System.out.println("保存成功"); } }
|