其他流

2016-11-12  本文已影响0人  VikingOldYoung

一、节点流

<br />
字节数组(字节 节点流,传送字节)传送的内容一般比较小
视频里说,一般是两台电脑内存之间的数据传输。所以用字节数组来。

简单的示例程序
<br />
读取操作

public static void read(byte[] src) throws IOException{
        //假设要读取的数据再其他电脑上。即传进来的那个src是其他电脑上的,需要保存在自己这里才能打印。
        
        //选择流,因为不用新方法,所以可以多态。用缓冲流来包装。他自己也不带缓冲
        InputStream byteinput=new BufferedInputStream(new ByteArrayInputStream(src));
        //定义读取的数组大小
        byte[] flush=new byte[30];
        //记录每次读取的长度
        int len;
        while(-1!=(len=byteinput.read(flush))){
            //把读取来的字节数组转换为字符串,方便示例程序查看
            String dest=new String(flush,0,len);
            //打印
            System.out.print(dest);
        }
    }

<br />
写入操作

public static byte[] write() throws IOException{
        //读取来的数据存放的数组
        byte[] dest;
        //选择流,这里因为要使用新的方法,也就不能用多态。不能用缓冲流包装。
        //但是这个ByteArrayOutputStream自带缓冲
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        //定义一个数组,读取的。假设他在另一台电脑的内存里
        String str=new String("中国人民站起来啦!!");
        byte[] info=str.getBytes();
        //把这个数组写到流的缓冲区里,即我们自己的电脑
        bos.write(info, 0, info.length);
        //从缓冲区获得这个数组
        dest=bos.toByteArray();
        //释放资源
        bos.close();
        
        return dest;
    }

<br />
文件相关

  1. 文件----->程序------->字节数组
  1. 字节数组-------->程序------->文件

示例程序
<br />
第一步的

public static byte[] ByteArrayFromFile(String srcPath) throws IOException {
        // 关联文件
        File src = new File(srcPath);
        // 选择流
        // 文件输入流,读取文件
        InputStream is = new BufferedInputStream(new FileInputStream(src));
        // 字节数组输出流,写入到字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] dest;
        // 操作
        byte[] flush = new byte[1024];
        int len;
        while (-1 != (len = is.read(flush))) {
            // 把flush里的读取出来的数据,写进流的缓冲里
            bos.write(flush, 0, len);

            bos.flush();
        }
        // 从流中获取数据
        dest = bos.toByteArray();
        // 关闭资源
        bos.close();
        is.close();
        // 返回读取进来的文件保存的字节数组
        return dest;
    }

<br />
第二步的

public static void FileFromByteArray(byte[] src, String destPath) throws IOException {
        // 关联文件
        File dest = new File(destPath);
        // 选择流
        InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
        OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
        // 操作
        byte[] flush = new byte[1024];
        int len;
        // 字节数组输入流,把字节读到flush里面
        while (-1 != (len = is.read(flush))) {
            // 文件输出流,把他写到文件里面
            os.write(flush, 0, len);
            // 刷新是个好习惯
            os.flush();
        }
        // 关闭资源
        os.close();
        is.close();
    }

<br />
然后是拷贝

public static void main(String[] args) {
        try {
            byte[] src = ByteArrayFromFile("F:/javaIotest/1.jpg");
            FileFromByteArray(src, "F:/javaIotest/33.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

<br />

二、处理流

处理基本数据类型+String(保留数据+类型)

输入流:DateInputStream 重点关注方法readXxx();
输出流:DateOutputStream 重点关注方法readXxx();

需要注意的是:读取写入,顺序要相同,不然会乱码。
常见的异常:
java.io.EOFException文件不对,即读到末尾了还没有
如果顺序不同不会抛出异常

常用于少量的需要保存数据类型的数据传输。避免判断解码需要消耗的资源和时间。

示例程序

public static void main(String[] args) {
        try {
            write();
            read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void read() throws IOException{
        
        DataInputStream dis=new DataInputStream(new BufferedInputStream(
        
                new FileInputStream(new File("f:/javaIotest/2.txt"))
                
                ));
        String str=dis.readUTF();
        int a=dis.readInt();
        double b=dis.readDouble();
        dis.close();
        System.out.println("String:"+str+"----->int:"+a+"----->double:"+b);
    }
    
    public static void write() throws IOException {
        //选择流,自己看咯。应该很简单
        DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(
                
                new FileOutputStream(new File("f:/javaIotest/2.txt"))
                
                ));
        String str="这是一个字符串啊!";
        int a=15;
        double b=12.54;
        
        dos.writeUTF(str);
        dos.writeInt(a);
        dos.writeDouble(b);
        dos.flush();
        
        dos.close();
    }
输出结果:
String:这是一个字符串啊!----->int:15----->double:12.54

<br />

处理引用类型(对象)保留数据+类型

反序列化(输入流)ObjectInputStream readObject();
序列化(输出流)ObjectOutputStream writeObject();
(方法里,上面基本类型和字符串的也都有,估计加了包装过程)

注意:

  1. 反序列化顺序必须和序列化一致,这和上面一样。
  2. 不是所有的对象都可以序列化,需要实现java.io.Serializable接口(内部的了些基本都实现了,数组也可以)
    不是所有的属性都需要序列化,可能只关注部分属性,不需要序列化的属性需要声明:transient
  3. Serializable接口,是个空接口,没有定义方法之类的,只是一个标识。
  4. 在读取的时候返回的是一个Object,可以先判断instanceof,然后再强转。

示例程序
1、写入

public static void write(String destPath) throws FileNotFoundException, IOException{
        //定义要储存的数据,这里name属性,声明为instanceof。所以不会被序列化
        Employee e1=new Employee("a",2000);
        Employee e2=new Employee("b",3000);
        //选择流,要用新方法,不能多态了。这里还用缓冲流包装了文件输出流
        ObjectOutputStream oos=new ObjectOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(new File(destPath))
                        )
                );
        //写入,注意顺序
        oos.writeObject(e1);
        oos.writeObject(e2);
        
        oos.flush();
        
        oos.close();
    }

2、读取

public static void read(String srcPath) throws FileNotFoundException, IOException, ClassNotFoundException{
        
        File src=new File(srcPath);
        
        ObjectInputStream ois=new ObjectInputStream(
                    new BufferedInputStream(
                            new FileInputStream(src)
                            )
                );
        
        Object o1=ois.readObject();
        Object o2=ois.readObject();
        if(o1 instanceof Employee){
            Employee e1=(Employee) o1;
            System.out.println(e1.getSalary());
            System.out.println(e1.getName());
        }
        if(o2 instanceof Employee){
            Employee e2=(Employee) o2;
            System.out.println(e2.getSalary());
        }
        ois.close();
    }

3、结果查看

public static void main(String[] args) {
        String destPath="f:/javaIotest/3.txt";
        try {
            read(destPath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
输出结果:
2000
null
3000

<br />

三、打印流(PrintStream)

打印流也是个处理流,这里单独列出来,表示他的重要性咯

三个常量
输出:System.out System.err
这俩都是PrintStream ,一样,只是在控制台输出颜色不一样。别的地方就没有区别了,语义不同,一个是标准的输出,一个一般输出错误信息
输入:System.in
这是InputStream

关于PrintStream

public static void test01() throws FileNotFoundException{
        
        System.out.println("You are beautiful!");
        //System.out也就是一个标准的输出流,打印到控制台
        PrintStream ps=System.out;
        ps.println("too");
        
        //这个PrintStream也就是一个处理流,底下是使用方法了。我这里给他输入到文件。后头那个true是他的构造器里带的,自动刷新
        ps=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("f:/javaIotest/print.txt"))),true);
        ps.print("你说啥!?");
    }

<br />
关于重定向
方法setIn(); setOut(); setErr();
里面装重新定向的流
回去的话就定向到控制台即可
FileDescriptor.in
FileDescriptor.out
FileDescriptor.err
程序

public static void test02() throws FileNotFoundException{
        System.out.println("Hello World!");
        //重定向,括号里面是他自己的那种流,这里我在PrintStream里选择了自动刷新,FileOutputStream里选择了追加
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("f:/javaIotest/print.txt"),true)),true));
        //这时候底下的System.out都是输出到那个文件啦
        System.out.println("这是一个帅哥!");
        
        //回到控制台,这个FileDescriptor.out相当于一个文件
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));
        System.out.println("Hello World!");
    }

<br />
自己包装一个类似Scanner的东西,主要是理解Scanner是个什么东西

public static void test03() throws IOException{
        //输入定位到控制台即可
        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(FileDescriptor.in)));
        System.out.println("请输入:");
        //把输入的那个转换为字符串
        String msg=new String(br.readLine());
        //再打印到控制台上
        System.out.println(msg);
        br.close();
    }

<br />
所以Scanner可以从文件输入啦
具体仔细的还有很多方法

public static void test04() throws FileNotFoundException{
        //好习惯,加个缓冲流
        InputStream is=new BufferedInputStream(new FileInputStream(new File("f:/javaIotest/poetry.txt")));
        //还有很多构造方法,可以看API
        Scanner s=new Scanner(is);
        while(s.hasNextLine()){
            String msg=s.nextLine();
            System.out.println(msg);
        }
        s.close();
    }
上一篇 下一篇

猜你喜欢

热点阅读