java学习第二十三天之 ByteArrayInputStream、DataInputStream、ObjectInputStream、Serializable、PipedOutputStream、

ByteArrayInputStream

package cn.inprint.demo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class ByteArrayStreamDemo {
    /**
    * @param args
    */
    public static void main(String[] args) {
//      用IO的读写思想操作数组
//      确定源
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream("abcde".getBytes());
        ByteArrayOutputStream byArrayOutputStream=new ByteArrayOutputStream();
//      确定目的。内置一个byte数组
        int by=0;
        while((by=byteArrayInputStream.read())!=-1){
            byArrayOutputStream.write(by);
        }
        System.out.println(byArrayOutputStream.toString());
    }
}

DataInputStream

package cn.inprint.demo;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamDemo {
    /**
    * @param args
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
        writeData();
        readData();
    }

    /**
     * @throws IOException 
     * 
     */
    private static void readData() throws IOException {
        FileInputStream fileInputStream=new FileInputStream("obj.txt");
        DataInputStream dataInputStream=new DataInputStream(fileInputStream);

        boolean b=dataInputStream.readBoolean();
        System.out.println(b);
        dataInputStream.close();
    }

    /**
     * @throws IOException 
     * 
     */
    private static void writeData() throws IOException {
//      写入一些基本的数据值,存储到文件
        FileOutputStream fileOutputStream=new FileOutputStream("obj.txt");
        DataOutputStream dataOutputStream=new DataOutputStream(fileOutputStream);
        dataOutputStream.writeBoolean(true);
        dataOutputStream.writeInt(1234);
        dataOutputStream.close();
    }
}

ObjectInputStream

package cn.inprint.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ObjectStreamDemo {
    /**
    * @param args
    * 用于操作对象的流对象,对象的序列化
    * ObjectInputStream  ObjectOutputStream
    * 特点:用于操作对象
    * 解决问题:可以将对象进行序列化和反序列化。注意:对象序列化一定要实现Serializable接口,为了给类定义一个serialVersionUID
    * 功能:ObjectInputStream  readObject()  ObjectOutputStream  writeObject()
    * 关键字:瞬态:transient
    * 
    * 
     * @throws IOException 
     * @throws ClassNotFoundException 
    */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        writeObj();
        readObj();
    }

    /**
     * @throws IOException 
     * @throws ClassNotFoundException 
     * 
     */
    private static void readObj() throws ClassNotFoundException, IOException {
//      定义流对象关联存储了对象文件
        FileInputStream fileInputStream=new FileInputStream("obj.txt");
//      建立用于读取对象的功能对象
        ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
        Person object=(Person)objectInputStream.readObject();
        System.out.println(object.toString());
    }

    /**
     * @throws IOException 
     * 
     */
    private static void writeObj() throws IOException {
        File file=new File("obj.txt");
        if(!file.exists()){
            System.out.println(123);
            file.createNewFile();
        }
//      明确存储对象的文件
        FileOutputStream fileOutputStream=new FileOutputStream("obj.txt");
//      给操作文件对象加入写入对象的功能
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
//      调用了写入对象的方法
        objectOutputStream.writeObject(new Person("大黑",1));
        objectOutputStream.close();
    }
}

Serializable

package cn.inprint.demo;

import java.io.Serializable;
/*
    Person类的对象如果需要序列化,就需要Serilizable标记接口
    该接口给需要需要序列化的类,提供了一个序列版本号 serialVersionUID"
    该版本号的目的在于验证序列化对象的发送者和接收者是否为该对象加载了与序列化兼容的类
*/
public class Person implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String name;
//  private int age;
    private transient int age;   //transident 瞬态,使用完马上消失

    public Person() {
        super();
    }
    /**
     * @param name
     * @param age
     */
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    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;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

}

PipedOutputStream

package cn.inprint.demo;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeStreamDemo {
    /**
    * @param args
    * 管道流:
    * 特点:读取管道和写入管道可以连接
    * 需要使用多线程技术,单线程 容易死锁
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
//      创建管道对象
        PipedInputStream pipedInputStream=new PipedInputStream();
        PipedOutputStream pipedOutputStream=new PipedOutputStream();

//      将两个流连接上
        pipedInputStream.connect(pipedOutputStream);
        new Thread(new Input(pipedInputStream)).start();
        new Thread(new Output(pipedOutputStream)).start();

    }

}

class Input implements Runnable{
    private PipedInputStream PipedInputStream;

    /**
     * @param pipedInputStream
     */
    public Input(java.io.PipedInputStream pipedInputStream) {
        super();
        PipedInputStream = pipedInputStream;
    }

    @Override
    public void run() {
        byte[] buf=new byte[1024];
        int len;
        try {
            len = PipedInputStream.read(buf);
            String string=new String(buf, 0, len);
            System.out.println(string);
            PipedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

class Output implements Runnable{
    private PipedOutputStream PipedOutputStream;

    /**
     * @param pipedOutputStream
     */
    public Output(java.io.PipedOutputStream pipedOutputStream) {
        super();
        PipedOutputStream = pipedOutputStream;
    }

    @Override
    public void run() {
        try {
            PipedOutputStream.write("Hi,管道来了".getBytes());
            PipedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

PrintStream

package cn.inprint.demo;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

public class printDemo {
    /**
    * @param printStream
    * IO包中的其他功能流对象
    * 功能流对象
    * 特点:解决的问题,特有的方法
    * 打印流--输出流
    * PrintStream(字节流)  PrintWriterStrean(字符流)
    * 特点:打印  不抛异常
    * 打印的目的:File对象,字符串路径,字节输出流
    * 解决问题:
    *   方便地打印
    *   它的打印方法可以保证数值的形式不变,写的是什么。目的就是什么
    * 
    * 
    * 
    * printWriter:一样具备打印功能
    *   目的:File对象,字符串路径,字节输出流,字符输出流
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
    /*  
        PrintStream pStream=System.out;
        pStream.println("HI");
//      等同于
        System.out.println("HI");
    */  

        printStreamDemo();
    }


    private static void printStreamDemo() throws IOException {
//      演示PrintStream的特有方法
//          创建PrintStrwm对象。目的就定为文件
        File dir=new File("D:\\java\\workspace\\Stage2\\src\\cn\\iolearn\\demo\\tempfile\\demo.txt");
        if(!dir.exists()){
            dir.createNewFile();
        }
        PrintStream printStream=new PrintStream(dir);
//      将数据打印到文件中
        printStream.write(3);//对字节流的write方法一次只写出一个字节 读出为e 保证数值的表现形式  其实原理就是讲数值转成字符串
        printStream.write("3".getBytes());//对字节流的write方法一次只写出一个字节 读出为byte
        printStream.print("我是大灰狼");//输入什么就写什么   保证数值的表现形式。其实原理就是将数值转成字符串
        printStream.close();
    }
}
package cn.inprint.demo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class printWriterDemo {
    /**
    * @param args
    * 演示一个小例子
    * 读取键盘录入,将数据转成大写显示在屏幕上
    */
    public static void main(String[] args) throws IOException {

//      键盘录入
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
//      定义目的
//      BufferedWriter bufferedWriter= new BufferedWriter(System.out);
        PrintWriter printWriter=new PrintWriter(System.out,true);//加入true参数,对println方法可以实现自动刷新

//      改变目的为文件,还想自动刷新
        printWriter=new PrintWriter(new FileWriter("1.txt"),true);//对流进行刷新

//      读一行写一行,键盘结束一定要定义结束标记
        String line=null;
        while((line=bufferedReader.readLine())!=null){
            if("over".equals(line)){
                break;
            }
            printWriter.println(line.toUpperCase());
        }
        printWriter.close();
        bufferedReader.close();//不需要关闭键盘录入这种标准输入    流一旦关闭后面获取不到
    }
}
package cn.inprint.demo;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccesFileDemo {
    /**
    * @param args
    * RandomAccessFile
    * 特点:1、只能操作文件
    * 2、既能读,又能写
    * 3、维护了一个byte数组,内部定义了字节流的读取和写入
    * 4、通过对指针的操作可以实现对文件的任意位置的读取和写入
    * 功能:getFilePointer  用于操作文件指针的方法
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
//      writeFile();
        readFile();
    }

    /**
     * @throws IOException 
     * 
     */
    private static void readFile() throws IOException {
        RandomAccessFile randomAccessFile=new RandomAccessFile("obj.txt", "r");
        byte[] buf=new byte[8];
        randomAccessFile.read(buf);
        String name= new String(buf);

        int age=randomAccessFile.readInt();
        System.out.println(name+":"+age);
        randomAccessFile.close();
    }

    /**
     * @throws IOException 
     * 
     */
    private static void writeFile() throws IOException {
//      创建一个随机访问文件的对象,文件不存在,则创建,若不存在,即不创建也不覆盖
        RandomAccessFile randomAccessFile=new RandomAccessFile("obj.txt", "rw");


        randomAccessFile.seek(8);//设置指针的位置 从此处开始写入数据
//      随机写入    写入姓名和年龄
        System.out.println(randomAccessFile.getFilePointer());
        randomAccessFile.write("小王八".getBytes());
        randomAccessFile.write(97);
        randomAccessFile.writeInt(45);//writeInt保证整数的字节原样性

        randomAccessFile.close();
    }
}
package cn.inprint.demo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

import javax.sound.midi.Sequence;

public class SequenceStreamDemo {
    /**
    * @param args
    * 序列流
    * 特点:流对象的有序排列
    * 解决问题:将多个输入流合并成一个输入流。将多个源合并成一个源,对于多源的操作会变得简单
    * 功能:特殊之处在构造函数上,一初始化就合并了多个流进来
    * 
    * 使用场景之一:对多个文件进行数据的合并。多个源对应一个项目
    * 
    * 演示序列流
    * 如何获取一个 Enumeriation呢?Vector有,但是效率低,使用ArrayList
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
        ArrayList<FileInputStream> a1=new ArrayList<FileInputStream>();
        for(int x=0;x<=3;x++){
            a1.add(new FileInputStream("D:\\java\\workspace\\Stage2\\src\\cn\\inprint\\demo\\tempfile\\"+x+".txt"));
        }
//      a1.add(new FileInputStream("D:\\java\\workspace\\Stage2\\src\\cn\\inprint\\demo\\tempfile\\1.txt"));

//      怎么通过ArrayList获取枚举接口,可以使用Collections工具类中的方法
        Enumeration<FileInputStream> enumeration=Collections.enumeration(a1);
        SequenceInputStream s1=new SequenceInputStream(enumeration);

//      创建目录、文件
        FileOutputStream fileOutputStream=new FileOutputStream("D:\\java\\workspace\\Stage2\\src\\cn\\inprint\\demo\\tempfile\\4.txt");

//      频繁的读写操作
//      创建缓冲区
        byte[] buf=new byte[124];
        int len=0;
        while((len=s1.read())!=-1){
            fileOutputStream.write(buf,0,len);
        }
        fileOutputStream.close();
        s1.close();//能把它所包含的集合内的流都关掉
    }
}
package cn.inprint.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class SplitFileTest {
    /**
    * @param args
     * @throws IOException 
    */
    public static void main(String[] args) throws IOException {
//      文件切割器
//      一个读取流对应多个输出流,而且生成的碎片文件都有有序的编号
        File srcFile=new File("obj.txt");
        File destDir=new File("myproperties");
        fileSpilt(srcFile,destDir);
    }

    /**
     * @param srcFile
     * @throws IOException 
     */
    private static void fileSpilt(File srcFile,File destDir) throws IOException {
        if(!srcFile.exists()){
            throw new RuntimeException(srcFile.getAbsolutePath()+"源文件不存在");
        }
        if(!destDir.exists()){
            destDir.mkdirs();
        }
//      读取源文件
        FileInputStream fileInputStream=new FileInputStream(srcFile);
//      创建目的引用
        FileOutputStream fileOutputStream=null;
//      创建一个缓冲区
        byte[] buf=new byte[1024*1024];
        int len=0;
        int count=0;
        while((len=fileInputStream.read())!=-1){
//          创建输出流
            File partFile=new File(destDir,(++count)+".part");
            fileOutputStream=new FileOutputStream(partFile);
            fileOutputStream.write(buf, 0, len);
            fileOutputStream.close();
        }
//      应该在产生隋品文件是,需要产生一个配置文件。记录碎片的个数和源文件的名字
//      配置文件中存储的键值信息,使用Properties集合
        Properties properties=new Properties();
        properties.setProperty("partcount", Integer.toString(count));
        properties.setProperty("filename", srcFile.getName());
        File configFile=new File(destDir,(++count)+".properties");

        fileOutputStream=new FileOutputStream(configFile);
        properties.store(fileOutputStream, "save part file info");
        fileInputStream.close();
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值