Day22_IO第四天

一、合并流(序列流)-SequenceInputStream(了解)java

概念
    合并流也叫序列流, 能够把多个字节输入流整合成一个, 从序列流中读取数据时, 将从被整合的第一个流开始读, 读完一个以后继续读第二个, 以此类推.

一、将两个输入流合并
   
   
   
   
public static void demo1() throws FileNotFoundException, IOException { FileInputStream fis1 = new FileInputStream("a.txt"); //建立字节输入流关联a.txt FileOutputStream fos = new FileOutputStream("c.txt"); //建立字节输出流关联c.txt int b1; while((b1 = fis1.read()) != -1) { //不断的在a.txt上读取字节 fos.write(b1); //将读到的字节写到c.txt上 } fis1.close(); //关闭字节输入流 FileInputStream fis2 = new FileInputStream("b.txt"); int b2; while((b2 = fis2.read()) != -1) { fos.write(b2); } fis2.close(); fos.close(); }

二、将多个输入流合并
   
   
   
   
public static void main(String[] args) throws IOException { //demo1(); //demo2(); FileInputStream fis1 = new FileInputStream("a.txt"); FileInputStream fis2 = new FileInputStream("b.txt"); FileInputStream fis3 = new FileInputStream("c.txt"); Vector<FileInputStream> v = new Vector<>(); //建立集合对象 v.add(fis1); //将流对象存储进来 v.add(fis2); v.add(fis3); Enumeration<FileInputStream> en = v.elements(); SequenceInputStream sis = new SequenceInputStream(en); //将枚举中的输入流整合成一个 FileOutputStream fos = new FileOutputStream("d.txt"); int b; while((b = sis.read()) != -1) { fos.write(b); } sis.close(); fos.close(); }


二、字节数组流(内存输出流)-ByteArrayOutputStream(掌握)web

概念
    该输出流能够向内存中写数据, 把内存看成一个缓冲区, 写出以后能够一次性获取出全部数据
.使用方式
建立对象: new ByteArrayOutputStream()
写出数据: write(int), write(byte[])
获取数据: toByteArray()

案例:定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(byte数组大小限制为5)


三、随机流-RandomAccessFile(了解)面试

概述
RandomAccessFile概述
RandomAccessFile类不属于流,是Object类的子类。但它融合了InputStream和OutputStream的功能。
支持对文件指定位置的读取和写入。换句话说写入和读取以前必须先指定位置

方法
    read(),write()配合seek(位置)
      一、先调用seek(10)在调用write,在10这个位置写入
      二、先调用seek(10)再调用read,读取10这个位置的数据

四、序列化流(对象操做流)-ObjectInputStream\ObjectOutputStream(掌握)数组

序列化概念
    把内存中的数据写入到硬盘
反序列化概念
    把硬盘中的数据读取到内存中
注意事项
    被序列化的类要实现 Serializable接口

解决黄色警告线问题
    给类增长 serialVersionUID属性
方法
    ObjectOutputStream的writeObject() 方法:将对象写入到文件
    ObjectInputStream的readObject()方法:将文件中的对象读取出来

演示:
    
    
    
    








* 将对象存储在集合中写出 Person p1 = new Person("张三", 23); Person p2 = new Person("李四", 24); Person p3 = new Person("马哥", 18); Person p4 = new Person("辉哥", 20); ArrayList<Person> list = new ArrayList<>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f.txt")); oos.writeObject(list); //写出集合对象 oos.close();* 读取到的是一个集合对象 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("f.txt")); ArrayList<Person> list = (ArrayList<Person>)ois.readObject(); //泛型在运行期会被擦除,索引运行期至关于没有泛型 //想去掉黄色能够加注解 @SuppressWarnings("unchecked") for (Person person : list) { System.out.println(person); } ois.close();


五、数据输入输出流DataInputStream\ DataOutputStream(了解)服务器

1.什么是数据输入输出流
* DataInputStream, DataOutputStream能够按照基本数据类型大小读写数据
* 例如按Long大小写出一个数字, 写出时该数据占8字节. 读取的时候也能够按照Long类型读取, 一次读取8个字节.
2.使用方式
* DataOutputStream(OutputStream), writeInt(), writeLong() 

DataOutputStream dos = new DataOutputStream(new FileOutputStream("b.txt"));
dos.writeInt(997);
dos.writeInt(998);
dos.writeInt(999);
dos.close();
* DataInputStream(InputStream), readInt(), readLong()

DataInputStream dis = new DataInputStream(new FileInputStream("b.txt"));
int x = dis.readInt();
int y = dis.readInt();
int z = dis.readInt();
System.out.println(x);
System.out.println(y);
System.out.println(z);
dis.close();


六、打印流(掌握PrintWriter)网络

概念
     该流能够很方便的将对象的toString()结果输出, 而且自动加上换行, 并且可使用自动刷出的模式

特色(掌握)
      A、能够写入任意类型数据
      B、能够自动刷新。必须先启动,而且是使用println.方法才有效,而咱们的print方法仅仅是能够写入任意类型的数据
     C、能够直接对文件进行写入
     D、底层调用的是转换流

注意事项(掌握)
     打印流只能输出数据,不能读取数据换句话说就是只能操做数据目的能操做数据源

PrintWriter 和 PrintStream的区别
     一、PrintWriter构造方法能够传入字符流或者字节流,而PrintStream只能传入字节流
     二、PrintWriter想要实现自动刷新构造方法必须手动指定,而PrintStream则不须要手动指定


使用
     咱们使用打印流就是为了使用自动刷新功能,因此如下只针对如何实现自动刷新进行案例演示
     
A、PrintWriter的使用方式(掌握)
          一、经过构造方法建立对象而且启用自动刷新功能
                    PrintWriter(OutputStrem out, boolean autoFlush);
                    PrintWriter(Writer out, boolean autoFlush);
          二、调用println\printf\format方法,只有调用这三个个方法才会自动调用flush方法
                
     
     
     
     
PrintWriter printWriter = newPrintWriter(new FileWriter("d.txt"),true);printWriter.printf("1");//仅仅写入数据而且刷新printWriter.println("2");//写入数据而且增长换行符,刷新printWriter.format("你好 %s", "张三");
B、PrintStream的使用方式
           一、经过构造方法建立对象而且启用自动刷新功能
                              PrintStream(OutputStrem out, boolean autoFlush);
          二、调用println\printf\format方法
          
    
    
    
    
PrintStream ps = newPrintStream(new FileOutputStream("a.txt"),true);//,true无关紧要ps.printf("你好");

               

七、Properties(掌握)app

一、概述
      Properties是一个键值对的 集合类,不是IO类 键和值都是字符串。能够从流中加载数据或者把数据保存到流中,是惟一一个能够和IO流集合使用的集合类
添加修改
public Object put(Object key, Object value)
添加修改
public Object setProperty(String key,String value)
调用的就是   put 方法
获取功能
public String get(String key)
获取
Public String getProperty(String key)
底层调用的是   get
Public String getProperty(String, String defaultValue)
底层调用   get, 若是找不到,返回   defaultValue
public Set<String> stringPropertyNames()
获取键集合
转换功能
public void list(PrintWriter out)
将当前的集合里面的键值保存到指定的文本中
 
public void list(PrintStream out)
public void load(InputStream inputStream)
从输入流中读取属性和列表
public void load(Reader reader)
public void store(OutputStream out, String comment)
把集合中的数据保存到文本中
public void store(Writer writer, String comments)
public Set keySet()
获取全部键的集合


注意:Properties类在之后Android中会有新的Properties替代,在EE中咱们会从新封装一个Properties工具类,由于Properties的缺点很明显,不能直接操做File对象
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo {
    /**
     * 经过Properties修改config.inf中的PhoneIndex,值修改为123
     * @param args
     */
    public static void main(String[] args) throws Exception {
        /*
         * 一、加载config.inf
         * 二、在内存修改config.inf中的phoneIndex
         * 三、将修改后的集合从新写入到配置文件
         */
        Properties p  = new Properties();
        p.load(new FileInputStream("config.inf"));
        
        
        p.put("PhoneIndex","123");
        p.store(new FileOutputStream("config.inf"), "PhoneIndex被修改过!!!");
        
    }
}
  

八、System类(掌握)dom

一、系统类,提供了静态的变量和方法供咱们使用
二、成员方法

public static void exit(int value)jvm

退出jvm,非0表示异常退出ide

public static long currentTimeMillis()

返回当前系统时间的毫秒值

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

从指定源数的指定位置开始复制,赋值到目标数组的指定位置

public static Properties getProperties();

获取当前系统的属性

public static String getProperty(String key)

获取指定键描述的系统属性

public static String getProperty(String key, String defaultValue)

获取指定键描述的系统属性,没有找到该键的话返回defaultValue


遍历Properties 
     
     
     
     
/** * 遍历系统描述Properties */ public static voidmain(String[] args) throws Exception{ Properties properties = System.getProperties(); Set<Object> keySet = properties.keySet(); for(Object key:keySet){ System.out.println(key +"*****"+properties.get(key)); } }

获取当前系统中的换行符
     
     
     
     
/** * 获取当前系统中的换行符 */ public static voidmain(String[] args) throws Exception{ String line = System.getProperty("line.separator"); System.out.println(line+"你好"); }


九、IO体系(掌握)




十、案例(掌握)

一、定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(byte数组大小限制为5)
二、两种方式实现键盘录入
三、改变标准输入输出流拷贝图片
四、我有一个学生类,这个类包含如下成员变量:姓名,语文成绩,数学成绩,英语成绩

         请从键盘录入5个学生信息,而后按照本身定义的格式存储到文本文件中。

         要求被存储的学生按照分数从高到低排序


五、定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(两种方式,不用字节数组流作)

十一、案例代码(掌握)

一、定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(byte数组大小限制为5)
      
      
      
      
package com.heima.test;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class Test1 { /** * @param args * 定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(byte数组大小限制为5) * * 分析: * 1,reda(byte[] b)是字节输入流的方法,建立FileInputStream,关联a.txt * 2,建立内存输出流,将读到的数据写到内存输出流中 * 3,建立字节数组,长度为5 * 4,将内存输出流的数据所有转换为字符串打印 * 5,关闭输入流 * @throws IOException */ public static void main(String[] args) throws IOException { //1,reda(byte[] b)是字节输入流的方法,建立FileInputStream,关联a.txt FileInputStream fis = new FileInputStream("a.txt"); //2,建立内存输出流,将读到的数据写到内存输出流中 ByteArrayOutputStream baos = new ByteArrayOutputStream(); //3,建立字节数组,长度为5 byte[] arr = new byte[5]; int len; while((len = fis.read(arr)) != -1) { baos.write(arr, 0, len); //System.out.println(new String(arr,0,len)); } //4,将内存输出流的数据所有转换为字符串打印 System.out.println(baos); //即便没有调用,底层也会默认帮咱们调用toString()方法 //5,关闭输入流 fis.close(); }}

二、两种方式实现键盘录入
       
       
       
       
package com.heima.otherio;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;public class Demo07_SystemIn { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //方式1 /*BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //InputStreamReader转换流 String line = br.readLine(); System.out.println(line); br.close();*/ //方式2 Scanner sc = new Scanner(System.in); String line = sc.nextLine(); System.out.println(line); sc.close(); }}

三、改变标准输入输出流拷贝图片
       
       
       
       
package com.heima.test;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.PrintStream;public class Test2 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.setIn(new FileInputStream("双元.jpg")); //改变标准输入流 System.setOut(new PrintStream("copy.jpg")); //改变标准输出流 InputStream is = System.in; PrintStream ps = System.out; byte[] arr = new byte[1024]; int len; while((len = is.read(arr)) != -1) { ps.write(arr, 0, len); } is.close(); ps.close(); }}
四、 我有一个学生类,这个类包含如下成员变量: 姓名,语文成绩,数学成绩,英语成绩

         请从键盘录入5个学生信息,而后按照本身定义的格式存储到文本文件中。

         要求被存储的学生按照分数从高到低排序


      
      
      
      
package cn.itcast;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.util.Comparator;import java.util.Scanner;import java.util.TreeSet;/* * 我有一个学生类,这个类包含一下成员变量:姓名,语文成绩,数学成绩,英语成绩。 * 请从键盘录入5个学生信息,而后按照本身定义的格式存储到文本文件中。 * 要求被存储的学生按照分数从高到低排序。 * * 分析: * A:写一个学生类,有4个成员变量。 * B:用Scanner实现键盘录入。 * C:把这多个学生进行存储。用集合。 * 那么,用哪一个集合呢? * 因为最终须要排序,因此,咱们选择TreeSet集合。 * D:遍历集合,获取到集合中的每个数据,用输出流写到文本文件。 * name chinese math english */public class StudentTest { public static void main(String[] args) throws IOException { // 写一个学生类,有4个成员变量。 System.out.println("学生信息录入开始"); // 定义TreeSet集合 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { // 主要条件 int num = s2.getSum() - s1.getSum(); // 分析次要条件 // 当总分相同,还得继续比较每一门的分数是否相同 int num2 = (num == 0) ? s1.getChinese() - s2.getChinese() : num; int num3 = (num2 == 0) ? s1.getMath() - s2.getMath() : num2; // 当语文,数学,英语成绩都相同的,咱们还得继续判断姓名是否相同。 int num4 = (num3 == 0) ? s1.getName().compareTo(s2.getName()) : num3; return num4; } }); for (int x = 0; x < 5; x++) { // 用Scanner实现键盘录入。 Scanner sc = new Scanner(System.in); // 键盘录入数据 System.out.println("请输入第" + (x + 1) + "个学生的姓名:"); String name = sc.nextLine(); System.out.println("请输入第" + (x + 1) + "个学生的语文成绩:"); int chinese = sc.nextInt(); System.out.println("请输入第" + (x + 1) + "个学生的数学成绩:"); int math = sc.nextInt(); System.out.println("请输入第" + (x + 1) + "个学生的英语成绩:"); int english = sc.nextInt(); // 把数据封装到学生对象中 Student s = new Student(); s.setName(name); s.setChinese(chinese); s.setMath(math); s.setEnglish(english); ts.add(s); } // 遍历集合,获取到集合中的每个数据,用输出流写到文本文件。 BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt")); bw.write("姓名\t语文\t数学\t英语"); bw.newLine(); bw.flush(); for (Student s : ts) { StringBuilder sb = new StringBuilder(); sb.append(s.getName()).append("\t").append(s.getChinese()) .append("\t").append(s.getMath()).append("\t") .append(s.getEnglish()); bw.write(sb.toString()); bw.newLine(); bw.flush(); } bw.close(); System.out.println("学生信息录入成功"); }}

       
       
       
       
package cn.itcast;public class Student { private String name; private int chinese; private int math; private int english; public Student() { } public Student(String name, int chinese, int math, int english) { super(); this.name = name; this.chinese = chinese; this.math = math; this.english = english; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getChinese() { return chinese; } public void setChinese(int chinese) { this.chinese = chinese; } public int getMath() { return math; } public void setMath(int math) { this.math = math; } public int getEnglish() { return english; } public void setEnglish(int english) { this.english = english; } public int getSum() { return this.chinese + this.math + this.english; }}


五、定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(两种方式,不用字节数组流作)
       
       
       
       
FileInputStream fileInputStream = new FileInputStream("LineNumberReader.java"); byte[] data = new byte[fileInputStream.available()]; int len = fileInputStream.read(data); System.out.println(new String(data,0,len));

十二、关于Serializable的Serial Version ID的讨论(了解)

     咱们编写一个实现了 Serializable 接口(序列化标志接口)的类, Eclipse 立刻就会给一个黄色警告:须要增长一个 Serial Version ID 为何要增长它是怎么计算出来的?有什么用?


    一、为何要增长?
               类实现 Serializable 接口的目的是为了将内存中的对象保存到本地磁盘或者经过网络传输(也就是可持久化)
无标题.png
       
       
       
       
package io;/** * 腾讯新闻手机客户端 * @author haoyongliang * */public class Consumer { public static void main(String[] args) { Person person = (Person)SerializationUtils.readObject(); System.out.println(person.getName()); }}


       
       
       
       
package io;/** * 腾讯新闻服务器 * @author haoyongliang * */public class Producer { public static void main(String[] args) { Person person = new Person(); person.setName("混世魔王"); SerializationUtils.writeObject(person); }}

       
       
       
       
package io;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;/** * 序列化工具类 * @author haoyongliang * */public class SerializationUtils { /** 序列化后的对象存储路径 */ private static final String FILE_NAME = "C://obj.bin"; public static void writeObject(Serializable s) { try ( ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME)); ){ oos.writeObject(s);//将对象写入到C://obj.bin } catch (Exception e) { e.printStackTrace(); } } public static Object readObject(){ Object obj = null; try( ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME)) ){ obj = ois.readObject(); }catch(Exception e){ e.printStackTrace(); } return obj; }}

1三、今天必须掌握的内容,面试题,笔试题。(掌握这个就能够放心学习后面的知识了)

一、说说合并流是干什么的
二、说说字节数组流是干什么的,底层是什么
三、说说随即流能够干什么
四、说说序列化流,而且经过序列化流将学生对象写入文件,而且将文件中的数据读取成学生对象
五、打印流有哪些,打印流能够读取数据吗?打印流的特色是什么,要想启用刷新功能,必须调用哪一个方法
六、代码题:定义一个文件输入流,调用read(byte[] b)方法,将a.txt文件中的内容打印出来(byte数组大小限制为5)
七、代码题:两种方式实现键盘录入
八、代码题:我有一个学生类,这个类包含如下成员变量:姓名,语文成绩,数学成绩,英语成绩

         请从键盘录入5个学生信息,而后按照本身定义的格式存储到文本文件中。

         要求被存储的学生按照分数从高到低排序

九、Properties的load store方法掌握






相关文章
相关标签/搜索