节点流

字节数组节点流

  • 输入流:ByteArrayInputStream read(byte[] b,int off,int len) close() 不用关闭

  • 输出流:ByteArrayOutputStream write(byte[] b,int off,int len) toByteArray()

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo08 {

    public static void main(String[] args) throws IOException {
        read(write());

    }

    public static void read(byte[] src) throws IOException {

        //选择流
        InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
        //操作
        byte[] flush = new byte[1024];
        int len = 0;
        while(-1!=(is.read(flush))){
            System.out.println(new String(flush));
        }
    }

    public static byte[] write(){
        //目的地
        byte[] dest;
        //选择流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //操作写出
        String msg = "操作与文件输入流一致";
        byte[] info = msg.getBytes();
        bos.write(info,0,info.length);
        //获取数据
        dest = bos.toByteArray();
        return dest;
    }

}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *1、文件  --程序->字节数组
 *1)、文件输入流     
 *      字节数组输出流
 *
 *
 * 2、字节数组  --程序->文件
 * 1)、字节数组输入流
 *      文件输出流
 * @author Administrator
 *
 */
public class ByteArrayDemo02 {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        byte[] data =getBytesFromFile("e:/xp/test/1.jpg");
        toFileFromByteArray(data,"e:/xp/test/arr.jpg");
    }
    /**
     * 2、字节数组  --程序->文件
     */
    public static void toFileFromByteArray(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[1];
        int len =0;
        while(-1!=(len =is.read(flush))){
            //写出到文件中
            os.write(flush, 0, len);
        }
        os.flush();

        //释放资源
        os.close();
        is.close();
    }

    /**
     * 1、文件  --程序->字节数组
     * @return
     * @throws IOException 
     */
    public static byte[] getBytesFromFile(String srcPath) throws IOException{
        //创建文件源
        File src =new File(srcPath);
        //创建字节数组目的地 
        byte[] dest =null;

        //选择流
        //文件输入流     
        InputStream is =new BufferedInputStream(new FileInputStream(src));
        //字节数组输出流 不能使用多态
        ByteArrayOutputStream bos =new ByteArrayOutputStream();

        //操作   不断读取文件 写出到字节数组流中
        byte[] flush =new byte[1024];
        int len =0;
        while(-1!=(len =is.read(flush))){
            //写出到字节数组流中
            bos.write(flush, 0, len);
        }
        bos.flush();

        //获取数据
        dest =bos.toByteArray();

        bos.close();
        is.close();     
        return dest;
    }
}

处理流

基本数据类型处理流

基本数据类型+String 保留数据+类型

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 1.输入流:DataInputStream
 * 2.输出流:DataOutputStream
 * java.io.EOFException :没有读取到相关的内容
 * @author Matrix42
 *
 */
public class Demo09 {

    public static void main(String[] args) throws IOException {
        write("F:/data.txt");
        read("F:/data.txt");

    }

    /**
     * 从文件读取数据+类型
     * @throws IOException 
     */
    public static void read(String destPath) throws IOException{
        //创建源
        File src = new File(destPath);
        //选择流
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(
                        new FileInputStream(src)));
        //操作 读取顺序与写入顺序一致 必须存在才能读取
        double point = dis.readDouble();
        long num = dis.readLong();
        String str = dis.readUTF();

        dis.close();

        System.out.println(point+" "+num+" "+str);
    }

    public static void write(String destPath) throws IOException {
        double point = 2.5;
        long num = 100L;
        String str = "数据类型";

        //创建源
        File dest = new File(destPath);
        //选择流
        DataOutputStream dos = new DataOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(dest)));
        //操作 写出的顺序 为读取准备
        dos.writeDouble(point);
        dos.writeLong(num);
        dos.writeUTF(str);

        dos.flush();
        dos.close();
    }

}

引用数据类型处理流

  • 反序列化:ObjectInputStream readObject()

  • 序列化:ObjectOutputStream writeObject()

反序列化顺序必须和反序列化一致
不是所有的对象都可以系列化,需要实现java.io.Serializable
不是所有的属性都需要序列化,使用transient表示这个属性不需要序列化

/**
 * 空接口只是标识
 */
public class Employee implements java.io.Serializable {
    //不需要序列化
    private transient String name;
    private double salary;
    public Employee() {
    }
    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;

public class Demo10 {

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        ser("F:ser.txt");
        read("F:ser.txt");

    }

    public static void read(String destPath) throws FileNotFoundException, IOException, ClassNotFoundException{
        File dest = new File(destPath);
        ObjectInputStream dis = new ObjectInputStream(
                new BufferedInputStream(
                        new FileInputStream(dest)));
        Object object = dis.readObject();
        if (object instanceof Employee) {
            Employee employee = (Employee) object;
            System.out.println(employee.getName());
            System.out.println(employee.getSalary());
        }
        dis.close();
    }

    public static void ser(String destPath) throws FileNotFoundException, IOException{
        Employee emp = new Employee("me",10000);
        File dest = new File(destPath);
        ObjectOutputStream dos = new ObjectOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(dest)));

        dos.writeObject(emp);
        dos.close();
    }

}

1.7新特性

  • try-with-resource
try(代码){
    关闭流
}catch(){
}

打印流

重定向输出到文件

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class Demo11 {

    public static void main(String[] args) throws FileNotFoundException {
        File src = new File("F:/out.txt");
        PrintStream ps = new PrintStream(src);
        ps.print("123");

    }

}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * 三个常量
 * 1、System.in  输入流  键盘输入
 * 2、System.out 输出流   控制台输出
 *    System.err
 *    
 * ==>重定向   
 * setIn()
 * setOut()
 * setErr()
 * FileDescriptor.in
 * FileDescriptor.out
 * @author Administrator
 *
 */
public class SystemDemo01 {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        //test1();
        //test2();
        //重定向
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("e:/xp/test/print.txt")),true));
        System.out.println("a");  //控制台  -->文件      
        System.out.println("test");
        //回控制台
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));
        System.out.println("back....");
    }
    public static void test2() throws FileNotFoundException{
        InputStream is =System.in;  //键盘输入
        is = new BufferedInputStream(new FileInputStream("e:/xp/test/print.txt"));
        Scanner sc = new Scanner(is);
        //System.out.println("请输入:");
        System.out.println(sc.nextLine());
    }

    public static void test1(){
        System.out.println("test");
        System.err.println("err");
    }

}

装饰设计模式

处理流就是对节点流的包装

public class Voice {
    private int voice =10;
    public Voice() {
    }
    public int getVoice() {
        return voice;
    }
    public void setVoice(int voice) {
        this.voice = voice;
    }

    public void say(){
        System.out.println(voice);
    }

}
/**
 * 扩音器
 * 类与类之间的关系
 * 1、依赖:形参|局部变量
 * 2、关联:属性
 *     聚合:属性 整体与部分 不一致的生命周期 人与手
 *     组合:属性 整体与部分 一致的生命周期  人与大脑
 * 3、继承:父子类关系
 * 4、实现: 接口与实现类关系
 */
public class Amplifier {
    private Voice voice;
    public Amplifier() {
    }
    public Amplifier(Voice voice) {
        super();
        this.voice = voice;
    }

    public void say(){
        System.out.println(voice.getVoice()*1000);
    }
}

文件的分割与合并

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.bjsxt.io.util.FileUtil;
public class SplitFile {
    //文件的路径
    private String filePath;
    //文件名
    private String fileName;
    //文件大小
    private long length;
    //块数
    private int size;
    //每块的大小
    private long blockSize;
    //分割后的存放目录
    private String destBlockPath;
    //每块的名称
    private List<String> blockPath;

    public SplitFile(){
        blockPath = new ArrayList<String>();
    }
    public SplitFile(String filePath,String destBlockPath){
        this(filePath,destBlockPath,1024);      
    }
    public SplitFile(String filePath,String destBlockPath,long blockSize){
        this();
        this.filePath= filePath;
        this.destBlockPath =destBlockPath;
        this.blockSize=blockSize;
        init();
    }

    /**
     * 初始化操作 计算 块数、确定文件名
     */
    public void init(){
        File src =null;
        //健壮性
        if(null==filePath ||!(((src=new File(filePath)).exists()))){
            return;
        }
        if(src.isDirectory()){
            return ;
        }
        //文件名
        this.fileName =src.getName();

        //计算块数 实际大小 与每块大小
        this.length = src.length();
        //修正 每块大小
        if(this.blockSize>length){
            this.blockSize =length;
        }
        //确定块数      
        size= (int)(Math.ceil(length*1.0/this.blockSize));
        //确定文件的路径
        initPathName();
    }

    private void initPathName(){
        for(int i=0;i<size;i++){
            this.blockPath.add(destBlockPath+"/"+this.fileName+".part"+i);
        }
    }

    /**
     * 文件的分割
     * 0)、第几块
     * 1、起始位置
     * 2、实际大小
     * @param destPath 分割文件存放目录
     */
    public void split(){    
        long beginPos =0;  //起始点
        long actualBlockSize =blockSize; //实际大小     
        //计算所有块的大小、位置、索引
        for(int i=0;i<size;i++){
            if(i==size-1){ //最后一块
                actualBlockSize =this.length-beginPos;
            }           
            spiltDetail(i,beginPos,actualBlockSize);
            beginPos+=actualBlockSize; //本次的终点,下一次的起点
        }

    }
    /**
     * 文件的分割 输入 输出
     * 文件拷贝
     * @param idx 第几块
     * @param beginPos 起始点
     * @param actualBlockSize 实际大小
     */
    private void spiltDetail(int idx,long beginPos,long actualBlockSize){
        //1、创建源
        File src = new File(this.filePath);  //源文件
        File dest = new File(this.blockPath.get(idx)); //目标文件
        //2、选择流
        RandomAccessFile raf = null;  //输入流
        BufferedOutputStream bos=null; //输出流
        try {
            raf=new RandomAccessFile(src,"r");
            bos =new BufferedOutputStream(new FileOutputStream(dest));

            //读取文件
            raf.seek(beginPos);
            //缓冲区
            byte[] flush = new byte[1024];
            //接收长度
            int len =0;
            while(-1!=(len=raf.read(flush))){               
                if(actualBlockSize-len>=0){ //查看是否足够
                    //写出
                    bos.write(flush, 0, len);
                    actualBlockSize-=len; //剩余量
                }else{ //写出最后一次的剩余量
                    bos.write(flush, 0, (int)actualBlockSize);
                    break;
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            FileUtil.close(bos,raf);
        }

    }
    /**
     * 文件的合并
     */
    public void merge(String destPath){
        //创建源
        File dest =new File(destPath);
        //选择流
        BufferedOutputStream bos=null; //输出流
        SequenceInputStream sis =null ;//输入流
        //创建一个容器
        Vector<InputStream> vi = new Vector<InputStream>();     
        try {
            for (int i = 0; i < this.blockPath.size(); i++) {
                vi.add(new BufferedInputStream(new FileInputStream(new File(this.blockPath.get(i)))));
            }   
            bos =new BufferedOutputStream(new FileOutputStream(dest,true)); //追加
            sis=new SequenceInputStream(vi.elements());         

            //缓冲区
            byte[] flush = new byte[1024];
            //接收长度
            int len =0;
            while(-1!=(len=sis.read(flush))){                       
                bos.write(flush, 0, len);
            }
            bos.flush();
            FileUtil.close(sis);
        } catch (Exception e) {
        }finally{
            FileUtil.close(bos);
        }       

    }
    /**
     * 文件的合并
     */
    public void merge1(String destPath){
        //创建源
        File dest =new File(destPath);
        //选择流
        BufferedOutputStream bos=null; //输出流
        try {
            bos =new BufferedOutputStream(new FileOutputStream(dest,true)); //追加
            BufferedInputStream bis = null;
            for (int i = 0; i < this.blockPath.size(); i++) {
                bis = new BufferedInputStream(new FileInputStream(new File(this.blockPath.get(i))));

                //缓冲区
                byte[] flush = new byte[1024];
                //接收长度
                int len =0;
                while(-1!=(len=bis.read(flush))){                       
                    bos.write(flush, 0, len);
                }
                bos.flush();
                FileUtil.close(bis);
            }
        } catch (Exception e) {
        }finally{
            FileUtil.close(bos);
        }       

    }

    public static void main(String[] args) {
        SplitFile split = new SplitFile("E:/xp/20130502/test/学员设置(20130502).xls","E:/xp/20130502",51);

        //System.out.println(split.size);

        //split.split();

        split.merge("E:/xp/20130502/test1.xls");
    }

}