生活中,你确定经历过这样的场景。当你编辑一个文本文件,忘记了 ctrl+s ,可能文件就白白编辑了。当你电脑上插入一个U盘,能够把一个视频,拷贝到你的电脑硬盘里。那么数据都是在哪些设备上的呢?键盘、内存、硬盘、外接设备等等。java
咱们把这种数据的传输,能够看作是一种数据的流动,按照流动的方向,之内存为基准,分为 输入input 和 输出output ,即流向内存是输入流,流出内存的输出流。数组
Java中I/O操做主要是指使用 java.io 包下的内容,进行输入、输出操做。输入也叫作读取数据,输出也叫作做写出数据。app
根据数据的流向分为:输入流和输出流。ide
格局数据的类型分为:字节流和字符流。函数
一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一 样如此。因此,字节流能够传输任意文件数据。在操做流的时候,咱们要时刻明确,不管使用什么样的流对象,底层传输的始终为二进制数据。学习
java.io.OutputStream 抽象类是表示字节输出流的全部类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。测试
public void close()
:关闭此输出流并释放与此流相关联的任何系统资源。public void flush()
:刷新此输出流并强制任何缓冲的输出字节被写出。public void write(byte[] b)
:将 b.length字节从指定的字节数组写入此输出流。public void write(byte[] b, int off, int len)
:从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。public abstract void write(int b)
:将指定的字节输出流。 OutputStream 有不少子类,咱们从最简单的一个子类开始。优化
java.io.FileOutputStream
类是文件输出流,用于将数据写出到文件。this
构造方法编码
public FileOutputStream(File file)
:建立文件输出流以写入由指定的 File对象表示的文件。public FileOutputStream(String name)
: 建立文件输出流以指定的名称写入文件。写出字节数据
FileOutputStream fos = new FileOutputStream("a.txt"); // 【write(int b)】 // 写入的十进制会转换成二进制存储到a.txt // 读取文件时,文件会按照指定的编码格式转换为对应的内容 fos.write(97); // 写入→97→110 0001→内存→读取→110 0001→ASCII→a fos.write(98); // 【 write(byte[] b)】 byte[]bs = {97,98,99,101,102}; fos.write(bs); // 【字符串转换字节数组getBytes()】 fos.write("你好".getBytes()); // 【write(byte[] b, int off, int len)指定长度的字节数组】 fos.write("xyz".getBytes(),0,2); fos.close();
数据追加续写
问题:
解决方案
代码
FileOutputStream fos = new FileOutputStream("a.txt",true); fos.write("我是新追加的数据".getBytes()); fos.close();
写出换行
系统中的换行
代码
FileOutputStream fos = new FileOutputStream("b.txt",true); for (int i = 0; i < 10; i++) { fos.write(("\r\n第" + i +"行数据:" + i*100).getBytes() ); } fos.close();
java.io.InputStream
抽象类是表示字节输入流的全部类的超类,能够读取字节信息到内存中。它定义了字节输入 流的基本共性功能方法。
public void close()
:关闭此输入流并释放与此流相关联的任何系统资源。
public abstract int read()
: 从输入流读取数据的下一个字节。
public int read(byte[] b)
: 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
使用数组读取,每次读取多个字节,减小了系统间的IO操做次数,从而提升了读写的效率,建议开发中使
用。
close方法,当完成流的操做时,必须调用此方法,释放系统资源。
java.io.FileInputStream 类是文件输入流,从文件中读取字节。
构造方法
FileInputStream(File file)
: 经过打开与实际文件的链接来建立一个 FileInputStream ,该文件由文件系 统中的 File对象 fifile命名。FileInputStream(String name)
: 经过打开与实际文件的链接来建立一个 FileInputStream ,该文件由文件 系统中的路径名 name命名。读取字节数据代码
// 建立字节输入流对象 FileInputStream fis = new FileInputStream("day07_IO//a.txt"); //【一次读取一个字节】 // 循环读取文件中的字节 int len = 0; while ((len=fis.read())!=-1){ System.out.print((char)len); } // 结果:ABC // 【一次读取多个字节】 // 将字节转换为字符串new Strig(bytes[]bts,int offset,int length); byte[]bts = new byte[10]; int len2 = 0; while ((len2=fis.read(bts))!=-1){ System.out.println(new String(bts,0,len2)); } fis.close();
原理
代码
public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); // 建立输入流对象-用来读取本地文件 FileInputStream fis = new FileInputStream("D:\\test.jpg"); // 建立输出流对象-用来写入本地文件 FileOutputStream fos = new FileOutputStream("day07_IO\\test_copy.jpg"); // 建立字节数组,一次从本地读取多个字节 byte[]bts = new byte[1024]; int len = 0; // 表示读取的有效字节个数 // 循环读取本地数据 while ((len=fis.read(bts))!=-1){ // 把实际读取的字节写入本地文件 fos.write(bts,0,len); } // 关闭输出流资源 fos.close(); // 关闭输入流资源 fis.close(); long e = System.currentTimeMillis(); System.out.println("复制成功!"); System.out.println("共耗时" + (e-s)+"毫秒"); }
当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是由于
一个中文字符可能占用多个字节存储。因此Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文
件。
public void close()
:关闭此流并释放与此流相关联的任何系统资源。public int read()
: 从输入流读取一个字符。public int read(char[] cbuf)
: 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。java.io.FileReader
类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区
注意事项
字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。 idea中UTF-8
字节缓冲区:一个字节数组,用来临时存储字节数据。
构造函数
代码
public static void main(String[] args) throws IOException { FileReader reader = new FileReader("day07_IO//a.txt"); // 【一次读取一个字符】 int len = 0; while ((len = reader.read())!=-1) { System.out.print((char)len); } // 【一次读取多个字符】 char[]chs = new char[1024]; int len = 0; while ((len = reader.read(chs))!=-1) { System.out.print(new String(chs,0,len)); // new String(char[]chars,int offset,int count); } reader.close(); }
java.io.Writer 抽象类是表示用于写出字符流的全部类的超类,将指定的字符信息写出到目的地。它定义了字节
输出流的基本共性功能方法。
void write(int c)
写入单个字符。void write(char[] cbuf)
写入字符数组。abstract void write(char[] cbuf, int off, int len)
写入字符数组的某一部分,offff数组的开始索引,len 写的字符个数。void write(String str)
写入字符串。void write(String str, int off, int len)
写入字符串的某一部分,offff字符串的开始索引,len写的字符个 数。void flush()
刷新该流的缓冲。void close()
关闭此流,但要先刷新它。java.io.FileWriter
类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
构造函数:
FileWriter(File file)
: 建立一个新的 FileWriter,给定要读取的File对象。FileWriter(String fileName)
: 建立一个新的 FileWriter,给定要读取的文件的名称。代码:
public static void main(String[] args) throws IOException { // 建立输出字符流对象 FileWriter fw = new FileWriter("day07_IO\\b.txt"); fw.write("你好"); fw.flush(); // flush将缓冲区的数据刷新到文件中,可继续写入 fw.write("我好"); fw.flush(); fw.write("你们好"); fw.close();// close 将缓冲区中的数据刷新到文件中,而且会释放输出流对象,后继没法继续输出 fw.write("真好"); // 异常 // 建立输出流对象,向指定的文件中追加写入数据 FileWriter fw2 = new FileWriter("day07_IO\\b.txt",true); for (int i = 0; i < 10; i++) { fw2.write("你好,新的世界!" + i + "\r\n"); } fw2.close(); }
注意事项:
处理方式:try-catch-finally
代码:
public static void main(String[] args) { // 建立输出流对象,向指定的文件中追加写入数据 FileWriter fw2 = null; try{ fw2 = new FileWriter("day07_IO\\b.txt",true); for (int i = 0; i < 10; i++) { fw2.write("你好,新的世界!" + i + "\r\n"); } }catch (IOException e) { e.printStackTrace(); }finally { if(fw2!=null){ try { fw2.close(); } catch (IOException e) { e.printStackTrace(); } } } }
处理方式:JDK7优化后的 try-with-resource 语句,该语句确保了每一个资源在语句结束时关闭。所谓的资源 (resource)是指在程序完成后,必须关闭的对象。
try (建立流对象语句,若是多个,使用';'隔开) { // 读写数据 } catch (IOException e) { e.printStackTrace(); }
代码:
public static void main(String[] args) { // 建立输出流对象,向指定的文件中追加写入数据 try(FileWriter fw2 = new FileWriter("day07_IO\\b.txt",true)){ for (int i = 0; i < 100; i++) { fw2.write("你好,新的世界!" + i + "\r\n"); } }catch (IOException e) { e.printStackTrace(); } }
JDK9中 try-with-resource 的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,一样能够自动关闭, 无需手动close
格式
// 被final修饰的对象 final Resource resource1 = new Resource("resource1"); // 普通对象 Resource resource2 = new Resource("resource2"); // 引入方式:直接引入 try (resource1; resource2) { // 使用对象 } catch (IOException e) { e.printStackTrace(); }
代码
public static void main(String[] args) throws IOException { // 建立输出流对象,向指定的文件中追加写入数据 FileWriter fw2 = new FileWriter("day07_IO\\b.txt",true); try(fw2){ for (int i = 0; i < 100; i++) { fw2.write("你好,新的世界!" + i + "\r\n"); } }catch (IOException e) { e.printStackTrace(); } }
java.util.Properties
继承于 Hashtable ,来表示一个持久的属性集。它使用键值结构存储数据,每一个键及其
对应值都是一个字符串。该类也被许多Java类使用,好比获取系统属性时, System.getProperties 方法就是返回
一个 Properties 对象。
构造方法:public Properties()
:建立一个空的属性列表。
基本的存储方法
public Object setProperty(String key, String value)
: 保存一对属性。public String getProperty(String key)
:使用此属性列表中指定的键搜索属性值。public Set<String> stringPropertyNames()
:全部键的名称的集合。与流相关的方法
public void load(InputStream inStream)
: 从字节输入流中读取键值对。
代码
public static void main(String[] args) throws IOException { // 获取系统相关的信息 System.out.println(System.getProperties()); // 建立一个属性集合 Properties pro = new Properties(); pro.setProperty("张三","180"); pro.setProperty("李四","189"); pro.setProperty("王五","178"); pro.setProperty("赵六","188"); // 读取属性集合中的数据 Set set = pro.keySet(); for (Object o : set) { System.out.println(pro.get(o)); } // 把集合中临时的数据输出到硬盘中 // pro.store(new FileWriter("day07_IO\\data.txt"),"save data"); // 读取本地文件中的数据(键值对的方式)到属性集合中 Properties pro2 = new Properties(); pro2.load(new FileReader("day07_IO\\data.txt")); System.out.println(pro2); }
缓冲流,也叫高效流,是对4个基本的 FileXxx 流的加强,因此也是4个流,按照数据类型分类:
缓冲流的基本原理,是在建立流对象时,会建立一个内置的默认大小的缓冲区数组,经过缓冲区读写,减小系统IO次数,从而提升读写的效率。
构造方法
public BufferedInputStream(InputStream in)
:建立一个 新的缓冲输入流。public BufferedOutputStream(OutputStream out)
: 建立一个新的缓冲输出流。代码测试
基本方式一次读写一个字节
public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); // 建立字节输入流,读取本地文件数据 FileInputStream fis = new FileInputStream("D:\\test.jpg"); // 建立字节输出流,向本地文件写入数据 FileOutputStream fos = new FileOutputStream("day08_IO\\test01.jpg"); // 定义变量表示读取的字节 int len = 0; // 循环遍历读取本地文件 while ((len=fis.read())!=-1) { // 把读取的字节写入本地 fos.write(len); } // 关闭输出流 fos.close(); // 关闭输入流 fis.close(); long e = System.currentTimeMillis(); System.out.println("共耗时:" + (e-s) + "毫秒"); // 161毫秒 }
基本方式一次读写多个字节
public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); // 建立字节输入流,读取本地文件数据 FileInputStream fis = new FileInputStream("D:\\test.jpg"); // 建立字节输出流,向本地文件写入数据 FileOutputStream fos = new FileOutputStream("day08_IO\\test02.jpg"); // 定义变量表示读取的有序字节个数 int len = 0; // 定义字节数组,表示一次要读取的字节数 byte[]bts = new byte[1024]; // 循环遍历读取本地文件 while ((len=fis.read(bts))!=-1) { // 把读取的字节写入本地 fos.write(bts,0,len); } // 关闭输出流 fos.close(); // 关闭输入流 fis.close(); long e = System.currentTimeMillis(); System.out.println("共耗时:" + (e-s) + "毫秒"); // 共耗时:7毫秒 }
缓冲流方式默认读写方式
public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); // 建立字节缓冲流输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\test.jpg")); // 建立字节缓冲流输出流f BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day08_IO\\test03.jpg")); // 循环读取本地数据 int len = 0; while ((len = bis.read())!=-1){ bos.write(len); } bos.close(); bis.close(); long e = System.currentTimeMillis(); System.out.println("共耗时:" + (e-s) + "毫秒"); // 共耗时:8毫秒 }
缓冲流方式指定字节读取
public static void main(String[] args) throws IOException { long s = System.currentTimeMillis(); // 建立字节缓冲流输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\test.jpg")); // 建立字节缓冲流输出流f BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day08_IO\\test04.jpg")); // 循环读取本地数据 int len = 0; byte[]bts = new byte[1024]; while ((len = bis.read(bts))!=-1){ bos.write(bts,0,len); } bos.close(); bis.close(); long e = System.currentTimeMillis(); System.out.println("共耗时:" + (e-s) + "毫秒"); // 共耗时:6毫秒 }
构造方法
public BufferedReader(Reader in)
:建立一个 新的缓冲输入流。public BufferedWriter(Writer out)
: 建立一个新的缓冲输出流。特有方法:字符缓冲流的基本方法与普通字符流调用方式一致,再也不阐述,咱们来看它们具有的特有方法。
public String readLine()
: 读一行文字。public void newLine()
: 写一行行分隔符,由系统属性定义符号。代码:
public static void main(String[] args) throws IOException { // 建立字符缓冲输出流 BufferedWriter bw = new BufferedWriter( new FileWriter("day08_IO\\01.txt")); for (int i = 0; i < 100; i++) { bw.write("贵在坚持!不仅是说说!" + i); bw.newLine(); } bw.close(); // 建立字符缓冲输入流 BufferedReader br = new BufferedReader(new FileReader("day08_IO\\01.txt")); String line; while ((line=br.readLine())!=null){ System.out.println(line); } br.close(); }
需求:读取本地文件中的文本,并排序后从新写入本地新的文件中
2.JavaScript 1.Java 4.PHP 6.C# 7.C 3.C++ 5.VB
代码:
public static void main(String[] args) throws IOException { // 建立HashMap对象存放读取的本地数据 HashMap<String,String > map = new HashMap<>(); // 建立字符缓冲区输入流,逐行读取本地数据 BufferedReader br = new BufferedReader(new FileReader("day08_IO\\02.txt")); String line; while ((line=br.readLine())!=null) { // 分割 String[]strs = line.split("\\."); map.put(strs[0],strs[1]); } br.close(); // 建立字符输出流 BufferedWriter bw = new BufferedWriter(new FileWriter("day08_IO\\03.txt")); for (int i = 1; i <= map.size(); i++) { bw.write(i +"."+ map.get(String.valueOf(i))); bw.newLine(); } bw.close(); }
计算机中储存的信息都是用二进制数表示的,而咱们在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制数转换以后的结果。按照某种规则,将字符存储到计算机中,称为编码 。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为解码 。好比说,按照A规则存储,一样按照A规则解析,那么就能显示正确的文本f符号。反之,按照A规则存储,再按照B规则解析,就会致使乱码现象。
字符编码Character Encoding : 就是一套天然语言的字符与二进制数之间的对应规则。
字符集charset:也叫编码表。是一个系统支持的全部字符的集合,包括各国家文字、标点符号、图形符号、数字等。
计算机要准确的存储和识别各类字符集符号,须要进行字符编码,一套字符集必然至少有一套字符编码常见字符集有ASCII字符集、GBK字符集、Unicode字符集等。可见,当指定了编码,它所对应的字符集天然就指定了,因此编码才是咱们最终要关心的。
ASCII字符集
ISO-8859-1字符集
GBxxx字符集
GB18030:最新的中文码表。收录汉字70244个,采用多字节编码,每一个字能够由1个、2个或4个字节组成。支持中国国内少数民族的文字,同时支持繁体汉字以及日韩汉字等。
Unicode字符集
在IDEA中,使用 FileReader 读取项目中的文本文件。因为IDEA的设置,都是默认的 UTF-8 编码,因此没有任何问题。可是,当读取Windows系统中建立的文本文件时,因为Windows系统的默认是GBK编码,就会出现乱码。
public static void main(String[] args) throws IOException { FileReader fr = new FileReader("D:\\a.txt"); int len = 0; while((len=fr.read())!=-1){ System.out.print((char)len); } fr.close(); } // 结果:��� 乱码
那么如何读取GBK编码的文件呢?
转换流 java.io.InputStreamReader
,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集能够由名称指定,也能够接受平台的默认字符集。
构造方法
InputStreamReader(InputStream in)
: 建立一个使用默认字符集的字符流。InputStreamReader(InputStream in, String charsetName)
: 建立一个指定字符集的字符流。代码
public static void main(String[] args) throws IOException { InputStreamReader fr = new InputStreamReader(new FileInputStream("D:\\a.txt"),"gbk"); int len = 0; while((len=fr.read())!=-1){ System.out.print((char)len); } fr.close(); } // 结果:你好
转换流 java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符 编码为字节。它的字符集能够由名称指定,也能够接受平台的默认字符集。
构造函数
OutputStreamWriter(OutputStream in)
: 建立一个使用默认字符集的字符流。OutputStreamWriter(OutputStream in, String charsetName)
: 建立一个指定字符集的字符流。代码
public static void main(String[] args) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("day08_IO\\04.txt"),"gbk"); osw.write("你好"); osw.close(); }
Java 提供了一种对象序列化的机制。用一个字节序列能够表示一个对象,该字节序列包含该 对象的数据 、 对象的 类型 和 对象中存储的属性 等信息。字节序列写出到文件以后,至关于文件中持久保存了一个对象的信息。 反之,该字节序列还能够从文件中读取回来,重构对象,对它进行反序列化。 对象的数据 、 对象的类型 和 对象中 存储的数据 信息,均可以用来在内存中建立对象。看图理解序列化:
java.io.ObjectOutputStream
类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
构造方法
public ObjectOutputStream(OutputStream out)
: 建立一个指定OutputStream的ObjectOutputStream。序列化操做
一个对象要想序列化,必须知足两个条件:
该类必须实现java.io.Serializable
接口, Serializable
是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出 NotSerializableException
。
该类的全部属性必须是可序列化的。若是有一个属性不须要可序列化的,则该属性必须注明是瞬态的,使用 transient
关键字修饰。
代码:
public class Person implements Serializable { // 实现Serializable,表示可序列化 private String name; private int age; private transient int height; // 该属性不会被序列化 public Person(String name, int age, int height) { this.name = name; this.age = age; this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return "姓名:" + name + ",年龄:"+ age + ",身高:" + height; } }
写出对象方法
public final void writeObject (Object obj) : 将指定的对象写出
代码
public static void main(String[] args) throws IOException { // 建立一我的类对象 Person p = new Person("张三",18,180); // 建立一个序列化输出流对象 ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("day08_IO\\person.txt")); // 把指定的对象序列化后写入本地文件 os.writeObject(p); os.close(); System.out.println("save a Object success"); }
ObjectInputStream反序列化流,将以前使用ObjectOutputStream序列化的原始数据恢复为对象。
构造方法
public ObjectInputStream(InputStream in);
: 建立一个指定InputStream的ObjectInputStream。
反序列化操做1
若是能找到一个对象的class文件,咱们能够进行反序列化操做,调用 ObjectInputStream 读取对象的方法:
代码:
public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream os = new ObjectInputStream(new FileInputStream("day08_IO\\person.txt")); Person p = (Person) os.readObject(); System.out.println(p); // 姓名:张三,年龄:18,身高:0 os.close(); } // 对于JVM能够反序列化对象,它必须是可以找到class文件的类。若是找不到该类的class文件,则抛出一个ClassNotFoundException 异常。
反序列化操做2
另外,当JVM反序列化对象时,能找到class文件,可是class文件在序列化对象以后发生了修改,那么反序列化操 做也会失败,抛出一个 InvalidClassException 异常。发生这个异常的缘由以下:
解决方案
代码
public class Person implements Serializable { // 实现Serializable,表示可序列化 // 定义序列化版本号 private static final long serialVersionUID = 10L; private String name; public int age; private transient int height; // 该属性不会被序列化 public Person(String name, int age, int height) { this.name = name; this.age = age; this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return "姓名:" + name + ",年龄:"+ age + ",身高:" + height; } }
平时咱们在控制台打印输出,是调用 print 方法和 println 方法完成的,这两个方法都来自于 java.io.PrintStream 类,该类可以方便地打印各类数据类型的值,是一种便捷的输出方式。
构造方法
public PrintStream(String fileName)
: 使用指定的文件名建立一个新的打印流。System.out 就是 PrintStream 类型的,只不过它的流向是系统规定的,打印在控制台上。不过,既然是流对象, 咱们就能够玩一个"小把戏",改变它的流向。
代码
public static void main(String[] args) throws IOException { // 打印在控制台 System.out.println("你好"); // 建立打印流,流向指定的本地文件 PrintStream ps = new PrintStream(new FileOutputStream("day08_IO\\print.txt")); // 设置System.out的打印流向指向ps System.setOut(ps); // 后续打印在print.txt文件中 System.out.println("你好1"); System.out.println("你好2"); System.out.println("你好3"); ps.close(); }