Java_流的操作规律(技巧)

流的操作规律

1. 明确源和目的。
数据源:就是需要读取,可以使用两个体系:InputStream、Reader;
数据汇:就是需要写入,可以使用两个体系:OutputStream、Writer;
2. 操作的数据是否是纯文本数据?
如果是:数据源:Reader
       数据汇:Writer 
如果不是:数据源:InputStream
        数据汇:OutputStream
3. 虽然确定了一个体系,但是该体系中有太多的对象,到底用哪个呢?
明确操作的数据设备。
数据源对应的设备:硬盘(File),内存(数组),键盘(System.in)
数据汇对应的设备:硬盘(File),内存(数组),控制台(System.out)。
4,需要在基本操作上附加其他功能吗?比如缓冲。
如果需要就进行装饰。

————————————————————————————————————

以下内容为引用资料

PrintStream(File file) :创建具有指定文件且不带自动行刷新的新打印流。


PrintStream(File file, String csn) :创建具有指定文件名称和字符集且不带自动行刷新的新打印流。

PrintStream(OutputStream out) :创建新的打印流。
PrintStream(OutputStream out, boolean autoFlush) :创建新的打印流。
PrintStream(OutputStream out, boolean autoFlush, String encoding) :创建新的打印流。
PrintStream(String fileName) :创建具有指定文件名称且不带自动行刷新的新打印流。
PrintStream(String fileName, String csn)

PrintStream可以操作目的:

1. File对象。2. 字符串路径。3. 字节输出流。

前两个都JDK1.5版本才出现。而且在操作文本文件时,可指定字符编码了。

当目的是一个字节输出流时,如果使用的println方法,可以在printStream对象上加入一个true参数。这样对于println方法可以进行自动的刷新,而不是等待缓冲区满了再刷新。最终print方法都将具体的数据转成字符串,而且都对IO异常进行了内部处理。

既然操作的数据都转成了字符串,那么使用PrintWriter更好一些。因为PrintWrite是字符流的子类,可以直接操作字符数据,同时也可以指定具体的编码。

PrintWriter:具备了PrintStream的特点同时,还有自身特点:
该对象的目的地有四个:1:File对象。2:字符串路径。3:字节输出流。4:字符输出流。

开发时尽量使用PrintWriter。

方法中直接操作文件的第二参数是编码表。
直接操作输出流的,第二参数是自动刷新。

//读取键盘录入将数据转成大写显示在控制台.
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//源:键盘输入
//目的:把数据写到文件中,还想自动刷新。
PrintWriter out = new PrintWriter(new FileWriter("out.txt"),true);//设置true后自动刷新
String line = null;
while((line=bufr.readLine())!=null){
    if("over".equals(line))
        break;
    out.println(line.toUpperCase());//转大写输出
}
    //注意:System.in,System.out这两个标准的输入输出流,在jvm启动时已经存在了。随时可以使用。当jvm结束了,这两个流就结束了。但是,当使用了显示的close方法关闭时,这两个流在提前结束了。
out.close();
bufr.close();
SequenceInputStream:序列流,作用就是将多个读取流合并成一个读取流。实现数据合并。

表示其他输入流的逻辑串联。它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。

这样做,可以更方便的操作多个读取流,其实这个序列流内部会有一个有序的集合容器,用于存储多个读取流对象。

该对象的构造函数参数是枚举,想要获取枚举,需要有Vector集合,但不高效。需用ArrayList,但ArrayList中没有枚举,只有自己去创建枚举对象。
但是方法怎么实现呢?因为枚举操作的是具体集合中的元素,所以无法具体实现,但是枚举和迭代器是功能一样的,所以,可以用迭代替代枚举。

合并原理:多个读取流对应一个输出流。
切割原理:一个读取流对应多个输出流。
import java.io.*;
import java.util.*;
class  SplitFileDemo{
    private static final String CFG = ".properties";
    private static final String SP = ".part";
    public static void main(String[] args) throws IOException{
        File file = new File("c:\\0.bmp");
        File dir = new File("c:\\partfiles");
        meger(dir);
    }
    //数据的合并。
    public static void meger(File dir)throws IOException{
        if(!(dir.exists() && dir.isDirectory()))
            throw new RuntimeException("指定的目录不存在,或者不是正确的目录");
        File[] files = dir.listFiles(new SuffixFilter(CFG));
        if(files.length==0)
            throw new RuntimeException("扩展名.proerpties的文件不存在");
        //获取到配置文件
        File config = files[0];
        //获取配置文件的信息。
        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream(config);
        prop.load(fis);
        String fileName = prop.getProperty("filename");
        int partcount = Integer.parseInt(prop.getProperty("partcount"));
        //--------------------------
        File[] partFiles = dir.listFiles(new SuffixFilter(SP));
        if(partFiles.length!=partcount)
            throw new RuntimeException("缺少碎片文件");
        //---------------------
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        for(int x=0; x<partcount; x++){
            al.add(new FileInputStream(new File(dir,x+SP)));
        }
        Enumeration<FileInputStream> en = Collections.enumeration(al);
        SequenceInputStream sis = new SequenceInputStream(en);
        File file = new File(dir,fileName);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=sis.read(buf))!=-1){
            fos.write(buf,0,len);
        }
        fos.close();
        sis.close();
    }
    //带有配置信息的数据切割。
    public static void splitFile(File file)throws IOException{
        //用一个读取流和文件关联。
        FileInputStream fis = new FileInputStream(file);
        //创建目的地。因为有多个。所以先创建引用。
        FileOutputStream fos = null;
        //指定碎片的位置。
        File dir = new File("c:\\partfiles");
        if(!dir.exists())
            dir.mkdir();
        //碎片文件大小引用。
        File f = null;
        byte[] buf = new byte[1024*1024];
        //因为切割完的文件通常都有规律的。为了简单标记规律使用计数器。
        int count = 0;
        int len = 0;
        while((len=fis.read(buf))!=-1){
            f = new File(dir,(count++)+".part");
            fos = new FileOutputStream(f);
            fos.write(buf,0,len);
            fos.close();
        }
        //碎片文件生成后,还需要定义配置文件记录生成的碎片文件个数。以及被切割文件的名称。
        //定义简单的键值信息,可是用Properties。
        String filename = file.getName();
        Properties prop = new Properties();
        prop.setProperty("filename",filename);
        prop.setProperty("partcount",count+"");
        File config = new File(dir,count+".properties");
        fos = new FileOutputStream(config);
        prop.store(fos,"");
        fos.close();
        fis.close();
    }
}
class SuffixFilter implements FileFilter{
    private String suffix;
    SuffixFilter(String suffix){
        this.suffix  = suffix;
    }
    public boolean accept(File file){
        return  file.getName().endsWith(suffix);
    }
}

RandomAccessFile:

特点:

  1. 该对象即可读取,又可写入。
  2. 该对象中的定义了一个大型的byte数组,通过定义指针来操作这个数组。
  3. 可以通过该对象的getFilePointer()获取指针的位置,通过seek()方法设置指针的位置。
  4. 该对象操作的源和目的必须是文件。
  5. 其实该对象内部封装了字节读取流和字节写入流。
    注意:实现随机访问,最好是数据有规律。
class RandomAccessFileDemo{
    public static void main(String[] args) throws IOException{
        write();
        read();
        randomWrite();
    }
    //随机写入数据,可以实现已有数据的修改。
    public static void randomWrite()throws IOException{
        RandomAccessFile raf = new RandomAccessFile("random.txt","rw");
        raf.seek(8*4);
        System.out.println("pos :"+raf.getFilePointer());
        raf.write("王武".getBytes());
        raf.writeInt(102);
        raf.close();
    }
    public static void read()throws IOException{
        RandomAccessFile raf = new RandomAccessFile("random.txt","r");//只读模式。
        //指定指针的位置。
        raf.seek(8*1);//实现随机读取文件中的数据。注意:数据最好有规律。
        System.out.println("pos1 :"+raf.getFilePointer());
        byte[] buf = new byte[4];
        raf.read(buf);
        String name = new String(buf);
        int age = raf.readInt();
        System.out.println(name+"::"+age);
        System.out.println("pos2 :"+raf.getFilePointer());
        raf.close();
    }
    public static void write()throws IOException{
        //rw:当这个文件不存在,会创建该文件。当文件已存在,不会创建。所以不会像输出流一样覆盖。
        RandomAccessFile raf = new RandomAccessFile("random.txt","rw");//rw读写模式
        //往文件中写入人的基本信息,姓名,年龄。
        raf.write("张三".getBytes());
        raf.writeInt(97);
        raf.close();
    }
}

管道流:

管道读取流和管道写入流可以像管道一样对接上,管道读取流就可以读取管道写入流写入的数据。

注意:

需要加入多线程技术,因为单线程,先执行read,会发生死锁,因为read方法是阻塞式的,没有数据的read方法会让线程等待。

public static void main(String[] args) throws IOException{
    PipedInputStream pipin = new PipedInputStream();
    PipedOutputStream pipout = new PipedOutputStream();
    pipin.connect(pipout);
    new Thread(new Input(pipin)).start();
    new Thread(new Output(pipout)).start();
}

对象的序列化目的:

将一个具体的对象进行持久化,写入到硬盘上。

注意:

静态数据不能被序列化,因为静态数据不在堆内存中,是存储在静态方法区中。

如何将非静态的数据不进行序列化?用transient 关键字修饰此变量即可。

Serializable:

用于启动对象的序列化功能,可以强制让指定类具备序列化功能,该接口中没有成员,这是一个标记接口。这个标记接口用于给序列化类提供UID。这个uid是依据类中的成员的数字签名进行运行获取的。如果不需要自动获取一个uid,可以在类中,手动指定一个名称为serialVersionUID id号。依据编译器的不同,或者对信息的高度敏感性。最好每一个序列化的类都进行手动显示的UID的指定。

import java.io.*;
class ObjectStreamDemo {
    public static void main(String[] args) throws Exception{
        writeObj();
        readObj();
    }
    public static void readObj()throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
        Object obj = ois.readObject();//读取一个对象。
        System.out.println(obj.toString());
    }
    public static void writeObj()throws IOException{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
        oos.writeObject(new Person("lisi",25)); //写入一个对象。
        oos.close();
    }
}
class Person implements Serializable{
    private static final long serialVersionUID = 42L;
    private transient String name;//用transient修饰后name将不会进行序列化
    public int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return name+"::"+age;
    }
}
DataOutputStream、DataInputStream:专门用于操作基本数据类型数据的对象。
DataOutputStream dos =  new DataOutputStream(new FileOutputStream("data.txt"));
    dos.writeInt(256);
    dos.close();

    DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
    int num = dis.readInt();
    System.out.println(num);
    dis.close();

ByteArrayInputStream:源:内存

ByteArrayOutputStream:目的:内存。

这两个流对象不涉及底层资源调用,操作的都是内存中数组,所以不需要关闭。
直接操作字节数组就可以了,为什么还要把数组封装到流对象中呢?因为数组本身没有方法,只有一个length属性。为了便于数组的操作,将数组进行封装,对外提供方法操作数组中的元素。

对于数组元素操作无非两种操作:设置(写)和获取(读),而这两操作正好对应流的读写操作。这两个对象就是使用了流的读写思想来操作数组。

//创建源:
    ByteArrayInputStream bis = new ByteArrayInputStream("abcdef".getBytes());
    //创建目的:
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int ch = 0;
    while((ch=bis.read())!=-1){
        bos.write(ch);
    }
    System.out.println(bos.toString());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值