IO包中的其他类 打印流,序列流,操作对象,管道流,RandomAccessFile,操作基本数据类型,操作字节数组

打印流,序列流,操作对象,管道流,RandomAccessFile,操作基本数据类型,操作字节数组

一、打印流:

该流提供了打印方法,可以将各种数据类型的数据都原样打印。

字节打印流
PrintStream
构造函数可以接收的参数类型
1、File对象 File
2、字符串路径 String
3、字节输出流 OutputStream

字符打印流
PrintWriter(更常用)
1、File对象 File
2、字符串路径 String
3、字节输出流 OutputStream
4、字符输出流 Writer

public class PrintStreamDemo_15 {

    public static void main(String[] args) throws IOException {
        
        BufferedReader bufr = 
                new BufferedReader(new InputStreamReader(System.in));
        
        PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);
                                                                //自动刷新
        
        String line = null;
        while((line=bufr.readLine())!=null)
        {
            if("over".equals(line))
                break;
            out.println(line.toUpperCase());
            //out.flush();
        }
        out.close();
        bufr.close();

    }

}
PrintStreamDemo_15

删除一个带内容的目录。

/*
删除一个带内容的目录。
删除原理:
在window中,删除目录从里面往外删除的。

既然是从里往外删除,就需要用到递归。
*/

public class RemoveDir_9 {

    public static void main(String[] args) {
        
        File dir = new File("aa");
        removeDir(dir);
    }
    public static void removeDir(File dir)
    {
        File[] files = dir.listFiles();
        for(int x=0;x<files.length;x++)
        {
            if(!files[x].isHidden()&&files[x].isDirectory())
            {
                removeDir(files[x]);
            }
            else
                System.out.println(files[x].toString()+":"+files[x].delete());
        }
        System.out.println(dir+":dir:"+dir.delete());
    }

}
RemoveDir_9

二、序列流

序列流(合并流)SequenceInputStream

public class SequenceInputStream_16 {

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

        Vector<FileInputStream> v = new Vector<FileInputStream>();
        
        v.add(new FileInputStream("1.txt"));
        v.add(new FileInputStream("2.txt"));
        v.add(new FileInputStream("3.txt"));
        
        Enumeration<FileInputStream> en = v.elements();
        SequenceInputStream sis = new SequenceInputStream(en);
        
        FileOutputStream fos = new FileOutputStream("4.txt");
        
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=sis.read(buf))!=-1)
        {
            fos.write(buf,0,len);
        }
        fos.close();
        sis.close();

    }

}
SequenceInputStream_16

三、操作对象

切割、合并文件

public class SpiieFile_17 {
    
    public static void main(String[] args) throws IOException
    {
        //spliFile();
        merge();
    }
    //合并
    public static void merge() throws IOException
    {
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        for(int x=1;x<=5;x++)
        {
            al.add(new FileInputStream("F:\eclipseWorkspace\Bixiangdong\splitfile\"+x+".part"));
        }
        final Iterator<FileInputStream> it = al.iterator();
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()
        {
            public boolean hasMoreElements()
            {
                return it.hasNext();
            }
            public FileInputStream nextElement()
            {
                return it.next();
            }
        };
        SequenceInputStream sis = new SequenceInputStream(en);
        
            FileOutputStream fos = new FileOutputStream("F:\eclipseWorkspace\Bixiangdong\splitfile\0.bmp");
            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 spliFile() throws IOException
    {
        FileInputStream fis = new FileInputStream("1.tmp");
        FileOutputStream fos = null;
        byte[] buf = new byte[1024*40];
        int len = 0;
        int count = 1;
        while((len=fis.read(buf))!=-1)
        {
            fos = new FileOutputStream("F:\eclipseWorkspace\Bixiangdong\splitfile\"+(count++)+".part");
            fos.write(buf,0,len);
            fos.close();
        }
        fis.close();
            
    }
}
SpiieFile_17
public class ObjectStreamDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        
        //writeObj();
        readObj();

    }
    public static void readObj() throws  IOException, ClassNotFoundException
    {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.object"));
        Person p = (Person)ois.readObject();
        System.out.println(p);
        ois.close();
    }
    public static void writeObj() throws IOException
    {
        ObjectOutputStream oos = 
                new ObjectOutputStream(new FileOutputStream("person.object"));
        oos.writeObject(new Person("lisi0",399,"kr"));//对象存在硬盘文件
        oos.close();
        
    }

}
class Person implements Serializable
{
    //自定义固定UID,类变换依然可以从文件中读取对象,为序列化方便
    public static final long serialVersionUID = 42L;
    private String name;
    transient int age;    //加关键字修饰,非静态成员也不能被序列化
    static String country = "cn";   //静态不能被序列化,静态在方法区,序列化只能序列化堆里的
    Person(String name,int age,String country)
    {
        this.name = name;
        this.age = age;
        this.country = country;
    }
    public String toString()
    {
        return name+":"+age+":"+country;
    }
}
ObjectStreamDemo

四、管道流

PipedInputStream   PipedOutputStream

class Read implements Runnable
{
    private PipedInputStream in;
    Read(PipedInputStream in)
    {
        this.in = in;
    }
    public void run()
    {
        try
        {
            byte[] buf = new byte[1024];
            System.out.println("读取前。。没有数据阻塞");
            int len = in.read(buf);
            System.out.println("读到。。阻塞结束");
            String s = new String(buf,0,len);
            System.out.println(s);
            in.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("管道读取流失败");
        }
    }
}
class Write implements Runnable
{
    private PipedOutputStream out;
    Write(PipedOutputStream out)
    {
        this.out = out;
    }
    public void run()
    {
        try
        {
            System.out.println("开始写入数据,等待6s后。");
            Thread.sleep(6000);
            out.write("piped lai le ".getBytes());
            out.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("管道输出流失败");
        }
    }
}
public class PipedStreamDemo_2 {

    public static void main(String[] args) throws IOException {
        
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        in.connect(out);
        Read r = new Read(in);
        Write w = new Write(out);
        new Thread(r).start();
        new Thread(w).start();
        

    }

}
PipedStreamDemo_2

五、RandomAccessFile

/*
RandomAccessFile

该类不是算是IO体系中子类。
而是直接继承自Object.

但是它是IO包中成员,因为它具备读和写功能。
内部封装一个数组,而且通过指针对数组的元素进行操作。
可以通过getFilePionter获取指针位置。
同时可以通过seek改变指针的位置。

起始完成读写的原理就是内部封装了字节输入流和输出流。

通过构造函数可以看出,该类只能操作文件。
而且操作文件还有模式。只读rw等。

如果模式为只读r,不会创建文件,会去读取一个已存在文件,如果该文件不存在,则会出现异常,
如果模式为rw,如果文件不存在,会自动创建,如果存在则不会覆盖。

用处:实现数据的分段写入。(如多线程下载)
*/

public class RandomAccessFileDemo_3 {

    public static void main(String[] args) throws IOException {
        
        writeFile();
        ReadFile();
        //writeFile_2();
    }
    public static void ReadFile() throws IOException
    {
        RandomAccessFile raf = new RandomAccessFile("ran.txt","r");
        
        //调整对象中的指针。
        //raf.seek(8);
        //跳过指定的字节数
        raf.skipBytes(10);
        byte[] buf = new byte[4];
        raf.read(buf);
        String name = new String(buf);
        int age = raf.readInt();
        System.out.println("name="+name);
        System.out.println("age="+age);
        raf.close();
    }
    public static void writeFile_2() throws IOException
    {
        RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
        raf.seek(8*0);
        raf.write("周七".getBytes());
        raf.writeInt(103);
        
        raf.close();
    }
    public static void writeFile() throws IOException
    {
        RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
        raf.write("李四".getBytes());
        raf.writeInt(97);
        raf.write("王五".getBytes());
        raf.writeInt(99);
        raf.close();
    }

}
RandomAccessFileDemo_3

六、操作基本数据类型

/*
DataInputStream 和DataOutputStream
可以用于操作基本数据类型的数据的流对象。
*/

public class DateIOStreamDemo_4 {

    public static void main(String[] args) throws IOException {
        
        //writeData();
        //readData();
        //writeUTFDemo();
        
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gbk.txt"),"gbk");
//        osw.write("您好");
//        osw.close();
        readUTFDemo();
    }
    public static void readUTFDemo() throws IOException
    {
        DataInputStream dis = new DataInputStream(new FileInputStream("utfdata.txt"));
        String s = dis.readUTF();
        System.out.println(s);
        dis.close();
    }
    public static void writeUTFDemo() throws IOException
    {
        //修改版,只能用对应的才能读出来
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("utfdata.txt"));
        
        dos.writeUTF("您好");
        dos.close();
    }
    public static void readData() throws IOException
    {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        //顺序要正确
        int num = dis.readInt();
        boolean b = dis.readBoolean();
        double d = dis.readDouble();
        System.out.println("num="+num);
        System.out.println("b="+b);
        System.out.println("d="+d);
        dis.close();
    }
    public static void writeData() throws IOException
    {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        
        dos.writeInt(234);//4个字节
        dos.writeBoolean(true);//一个字节
        dos.writeDouble(9887.543);//8个字节
        dos.close();
    }

}
DateIOStreamDemo_4

七、操作字节数组

/*
用于操作字节数据的流对象。

ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组。

ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组,
这就是数据目的地。

因为这两个流对象都操作的数组,并没有使用系统资源。
所以,不用进行close关闭。

在流操作规律讲解时,
源设备:
键盘 System.in, 硬盘 FileStream,内存ArrayStream.
目的设备:
控制台 System.out,硬盘FileStream,内存ArrayStream.

用流的读写思想来操作数组。
*/

public class ByteArreayIOStream_5 {

    public static void main(String[] args) {
        
        //数据源
        ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEFD".getBytes());
        //数据目的
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        
        //源:硬盘    目的:内存
        
        
        int by = 0;
        while((by=bis.read())!=-1)
        {
            bos.write(by);
        }
        System.out.println(bos.size());
        System.out.println(bos.toString());
        
        //用流的思想操作数组
        //提供代码复用性,
        
        //bos.writeTo(new FileOutputStream("a,txt"));
    }

}
ByteArreayIOStream_5
原文地址:https://www.cnblogs.com/cailingsunny/p/4698836.html