IO流

1.字节流

FileInputStream&FileOutputStream

/**
 * 字节流可以处理所有的文件类型
 * @author Administrator
 *    复制一个文本
 */

public class MyFileInputStream {
    public static void main(String[] args) throws Exception {
        //创建一个输入、输出流,其中的路径斜杠可以使用/或者\\
        FileInputStream fis=new FileInputStream("e:/电脑优化及公司ftp地址.txt");
        FileOutputStream fos=new FileOutputStream("e:/bak.txt",false);
        int data=0;
        while((data=fis.read())!=-1){
            fos.write(data);
        }
        //关闭流
        fis.close();
        fos.close();
    }

}

当数据量大的时候就比较慢

2.使用read(byte[]);

public class MyFileInputStream {
    public static void main(String[] args) throws Exception {
        //创建一个输入、输出流,其中的路径斜杠可以使用/或者\\
        FileInputStream fis=new FileInputStream("e:/电脑优化及公司ftp地址.txt");
        FileOutputStream fos=new FileOutputStream("e:/bak.txt",false);
        byte[] data5=new byte[5];
        int i=0;
        while((i=fis.read(data5))!=-1){ //从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中b - 存储读入数据的缓冲区。 
                                        //返回:读入缓冲区的总字节数;如果因为已经到达流末尾而不再有数据可用,则返回 -1。
            fos.write(data5,0,i);       //直接写会碰到一种情况,当最后读取的不够5个时,写却写了5个,导致数据不正确,
                                        //使用write(byte[] b,int off, int len)
                                        //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
        }
        //关闭流
        fis.close();
        fos.close();
    }

}

3.直接写入字符串要先转换为byte

public class 字符串操作 {

    public static void main(String[] args) throws Exception {
        FileOutputStream fos=new FileOutputStream("e:/bak.txt",true); //true表示追加
        String str="中华人民共和国万岁!+!@@#@#¥%%……&*。,【】、'\323246ddsxg~`!@#$%^&*()-=——+";
        byte[] bytes = str.getBytes();
        fos.write(bytes);
        fos.close();
    }

}

4.BufferedInputStream&BufferedOutputStream

public class BufferedInputStream_My {

    public static void main(String[] args) throws Exception {
        FileInputStream fis=new FileInputStream("e:/bak.txt");
        FileOutputStream fos=new FileOutputStream("e:/bak1.txt");
        //包装一重,等于可以在buffered中设置缓冲区大小。
        BufferedInputStream bis=new BufferedInputStream(fis,8);
        BufferedOutputStream bos=new BufferedOutputStream(fos,8);
        int length=0;
        while((length=bis.read()) != -1){
            System.out.println(length);
            bos.write(length);
            bos.flush();                 
        }
        bis.close();
        bos.close();
    }

}

5.字符流FileReader&FileWriter

public class FileReader_m {

    public static void main(String[] args) throws Exception {
        FileReader fr=new FileReader("e:/bak.txt");
        FileWriter fw=new FileWriter("e:/bak1.txt");
        int data=0;
        char[] c=new char[10];
        while((data=fr.read(c))!=-1){
            fw.write(c, 0, data);;
        }
        fr.close();
        fw.close();
    
    }

}

6.PrintWriter,可以打印换行println,普通的只能打印字符串”\n”代替了

public class line {

    public static void main(String[] args) throws Exception {
        PrintWriter pw=new PrintWriter(new BufferedOutputStream(new FileOutputStream("e:/printWiter.txt", true), 10),true);
        pw.print("gg");
        pw.print("gg");
        pw.print("gg");
        pw.println();
        pw.close();
    }

}

7.BufferedWriter&BufferedReader

public class writer {

    public static void main(String[] args) throws Exception {
        FileWriter fw=new FileWriter("e:/printWter.txt");
        FileReader fr=new FileReader("e:/printWiter.txt");
        BufferedReader br=new BufferedReader(fr);
        BufferedWriter bw=new BufferedWriter(fw);
        String data="";
        while((data=br.readLine())!=null){
            bw.write(data+"\r\n");
            bw.flush();
        }
        br.close();
        fw.close();
    }

}

8.RandomAccessFile 此类的实例支持对随机访问文件的读取和写入。

public class random {

    public static void main(String[] args) throws Exception {
        //可读写的文件流
        RandomAccessFile ra=new RandomAccessFile("e:/bak.txt", "rw"); //mode可以为"r","rw","rws","rwd"/read,write,读写同步,读写同步(减少执行的 I/O 操作数量)
        String data="";
        while((data=ra.readLine())!=null){
            System.out.println(new String(data.getBytes("ISO-8859-1"),"gb2312"));
        }
        /** 写入 */
        ra.write("哈哈哈\r\n".getBytes("gb2312"));
        ra.close();
    }
}

读取图片使用read

public class random {
    public static void main(String[] args) throws Exception {
        //可读写的文件流
        RandomAccessFile ra=new RandomAccessFile("e:/640.jpg", "rw"); //mode可以为"r","rw","rws","rwd"/read,write,读写同步,读写同步(减少执行的 I/O 操作数量)
        RandomAccessFile ras=new RandomAccessFile("e:/gg.jpg", "rw");
        ra.seek(0); //设置起始位置
        int length=0;
        byte[] data=new byte[10000];
        while((length=ra.read(data))!=-1){
            ras.write(data, 0, length);
            System.out.println(ra.getFilePointer());//获得末尾位置
        }
        /** 写入  */
        ra.close();
        ras.close();
    }
}


9.ObjectOutputStream&ObjectInputStream可以读取对象,一般用于网络传输和保存到本地。要实现序列化。否则报错:java.io.NotSerializableException

public class Student implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private  String Country;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public  String getCountry() {
        return Country;
    }
    public  void setCountry(String country) {
        Country = country;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", Country=" + Country
                + "]";
    }
    
}
public class Test {
    public static void test1() throws  Exception{
        Student s1=new Student();
        s1.setId(1);
        s1.setName("joe");
        s1.setCountry("中国");
        
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("e:\\obj.txt"));
        oos.writeObject(s1);
        oos.close();
        
    }
    public static void main(String[] args) throws Exception {
        test1();
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("e:/obj.txt"));
        Student stu = (Student)ois.readObject();
        System.out.println(stu.toString());
    }

}

结果:文本信息:

image

控制台打印:

Student [id=1, name=joe, Country=中国]


10.DataInputStream&DataOutputStream如出一辙

public class dataStream {
    public static void main(String[] args) throws Exception {
        DataInputStream dis=new DataInputStream(new FileInputStream("e:/bak.txt"));
        DataOutputStream dos=new DataOutputStream(new FileOutputStream("e:\\gg.txt"));
        int length=0;
        while((length=dis.read())!=-1){
            dos.write(length);
        }
        dos.close();
        dis.close();
    }
}


11.InputStreamReader

public class text {

    public static void main(String[] args) throws Exception {
        FileInputStream fis=new FileInputStream("e:/bak1.txt");
        InputStreamReader isr=new InputStreamReader(fis, "gb2312");
        char[] c=new char[1024];
        while(isr.read(c)!=-1){
            System.out.println(c);
        }
    }

}

在这里测试的时候我发现了一个问题,前面复制出来的通过\r\n获得的换行,在txt中就是正常的显示,但在word或者其他编辑软件会换2次行,其实\n是换行的意思,\r是回车换行的意思,所以这样。导致我后面再复制这个复杂出来的文本时打印怎么发现多了一下换行,其实就是这个原因。

 

12.管道流。用于线程之间的通信

/**
 * 
 * 首先需要明确一点的是管道流本身就不建议在一个线程中使用,这是因为向输出流中写的数据,都会存到输入流内部的一个1024字节大小的数组中,
 * 如果写的内容超过这个数组的大小,所以用包装流包装他让他缓存区变大
 * 而且没有被输入流读取的话,输出流所在的线程就会等待,这时,如果是在同一个线程中,该线程就会死锁,这是sun在管道流中明确指明的 不推荐在同一个线程中使用。
 * 
 */

public class Pipe {
    public static void main(String args[]) { // 管道流要注意连接,通过线程操作
        PipedInputStream pios = new PipedInputStream();
        PipedOutputStream pops = new PipedOutputStream();

        try {
            pops.connect(pios); // 连接,随便连,那个先都可以。
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Sender s = new Sender(pops);
        Receive r = new Receive(pios);
        s.start();
        r.start();
    }
}

class Sender extends Thread { // 使用数据流包装管道流,添加额外功能
    private DataOutputStream dos = null;

    public Sender(PipedOutputStream pos) { // 初始化
        dos = new DataOutputStream(pos);
    }

    @Override
    public void run() {
        try {

            dos.writeUTF("hello");
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Receive extends Thread {
    private DataInputStream dis = null;

    public Receive(PipedInputStream pis) {
        dis = new DataInputStream(pis);
    }

    @Override
    public void run() {
        try {
            System.out.println(dis.readUTF());
            dis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

转载于:https://www.cnblogs.com/lq625424841/p/7194282.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值