首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java之IO流补充

Java之IO流补充

作者头像
二十三年蝉
发布2018-02-28 10:56:43
9260
发布2018-02-28 10:56:43
举报
文章被收录于专栏:闻道于事闻道于事

IO流例子

package com.hanqi.maya.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class Test3 {
    public static void main(String[] args) {
        File file=new File("E:\\ceshi.txt");
        File ofile=new File("E:\\cewshi8.txt");
        
        Reader r=null;
        
        try {
            r=new FileReader(file);
            Writer w=new FileWriter(ofile,true);//true表示追加,不加则原本表示替换
            BufferedReader br=new BufferedReader(r);
            BufferedWriter bw=new BufferedWriter(w);
            String s=null;
            while((s=br.readLine())!=null){
                System.out.print(s);
                bw.write(s);
                bw.flush();//一个好的编程习惯应该在此处使用flush,写入需要用 flush 刷新流,否则会在缓冲区不写入文件
            }
            br.close();
            bw.close();//调用该方法前会自动调用 flush 
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件流(字节流, 字符流)

字节流例子

 1 //字节输入流
 2 //读取内容并输出读取多少字节
 3 package com.zijie;
 4 
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.IOException;
 8 
 9 public class TestFileInputStream
10 {
11     public static void main(String[] args) {
12         int b = 0;
13 
14         FileInputStream in = null;
15         try{
16             in = new FileInputStream("E:\\Java\\0801 流后传 线程\\线程.txt");
17         } catch(FileNotFoundException e) {
18             System.out.println("找不到指定的文件");
19             System.exit(-1);
20         }
21 
22         try{
23             long num = 0;
24             // 返回-1的话就表示已经读到了文件的结尾
25             while((b = in.read()) != -1) {
26                 System.out.print((char)b);
27                 num++;
28             }
29             in.close();
30             System.out.println("\n\n共读取了" + num + "个字节");
31         } catch(IOException e1) {
32             System.out.println("读取文件时出现异常");
33             System.exit(-1);
34         }
35     }
36 }
 1 //字节输出流
 2 //复制文件
 3 package com.zijie;
 4 
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 public class TestFileOutputStream {
11     public static void main(String[] args) {
12         int b = 0;
13         FileInputStream in = null;
14         FileOutputStream out = null;
15         try {
16             in = new FileInputStream("E:\\Java\\0801 流后传 线程\\线程.txt");
17             // OutputStream有这个文件就往这个文件里面写, 没有的话就自动创建一个
18             out = new FileOutputStream("E:\\Java\\0801 流后传 线程\\线程-ceshi.txt");
19             // 一边读, 一边写
20             while ((b = in.read()) != -1) {
21                 out.write(b);
22             }
23         } catch (FileNotFoundException e) {
24             System.out.println("找不到指定文件");
25             System.exit(-1);
26         } catch (IOException e) {
27             System.out.println("文件复制出错");
28             System.exit(-1);
29         }
30         System.out.println("文件成功复制");
31     }
32 }

字符流例子

 1 //字符输入流
 2 //读取文件内容
 3 package com.zifu;
 4 
 5 import java.io.FileNotFoundException;
 6 import java.io.FileReader;
 7 import java.io.IOException;
 8 
 9 public class TestFileReader {
10     public static void main(String[] args) {
11         FileReader fr = null;
12         int c = 0;
13         try {
14             fr = new FileReader("E:\\Java\\0801 流后传 线程\\线程.txt");
15             while ((c = fr.read()) != -1) {
16                 System.out.print((char) c);
17             }
18             fr.close();
19         } catch (FileNotFoundException e) {
20             System.out.println("文件未找到");
21             System.exit(-1);
22         } catch (IOException e) {
23             System.out.println("读取文件时出现异常");
24             System.exit(-1);
25         }
26     }
27 }
 1 //字符输入流
 2 //不断写入int型,写入为ASCII表
 3 package com.zifu;
 4 
 5 import java.io.FileWriter;
 6 import java.io.IOException;
 7 
 8 public class TestFileWriter {
 9     public static void main(String[] args) {
10         FileWriter fw = null;
11         try {
12             fw = new FileWriter("E:\\Java\\0801 流后传 线程\\线程-ceshi1.txt");
13             for (int i = 1; i <= 50000; i++) {
14                     fw.write(i);
15             }
16         } catch (IOException e) {
17             System.out.println("写入文件出错 !");
18             System.exit(-1);
19         }
20     }
21 }

缓冲流

 1 package com.buffer;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 
 8 public class TestBufferStream {
 9     public static void main(String[] args) {
10 
11         byte[] bb = new byte[50];
12         try {
13             FileInputStream fis = new FileInputStream("E:\\Java\\0801 流后传 线程\\ceshi.txt");
14             BufferedInputStream bis = new BufferedInputStream(fis);//将文件字节流,转换成带缓冲的输入字节流
15             int c = 0;
16             System.out.println((char)bis.read());
17             System.out.println((char)bis.read());
18 /*            while((c = bis.read()) != -1) {
19                 System.out.print((char)c+", ");
20             }*/
21             // 标记到第30的位置再开始读数据
22             bis.mark(100);//见的总承包 mark的方法 InputStream
23             
24             for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
25                 System.out.print((char)c);
26             }
27             System.out.println();
28             // 回到mark标记的那个地方
29             bis.reset();//见的总承包reset的方法InputStream 。 
30             for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
31                 System.out.print((char)c);
32             }
33             bis.close();
34         } catch (FileNotFoundException e) {
35             e.printStackTrace();
36         } catch (IOException e) {
37             e.printStackTrace();
38         }
39         
40     }
41 }
 1 package com.buffer;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileReader;
 7 import java.io.FileWriter;
 8 import java.io.IOException;
 9 
10 public class TestBufferRW {
11     public static void main(String[] args) {
12         
13         try {
14             BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\Java\\0801 流后传 线程\\ceshi.txt"));
15             BufferedReader br = new BufferedReader(new FileReader("E:\\Java\\0801 流后传 线程\\ceshi.txt"));
16             
17             String s = null;
18             
19             for (int i = 0; i < 100; i++) {
20                 s = "" + Math.random();
21                 //bw.write(s);
22                 bw.append(s);//写入文件
23                 bw.newLine();
24             }
25             
26             bw.flush();
27             // 特别好用的方法, readLine
28             while((s = br.readLine()) != null) {//获取文件内容输出到控制台
29                 System.out.println(s);
30             }
31             br.close();
32             bw.close();
33         } catch (FileNotFoundException e) {
34             e.printStackTrace();
35         } catch (IOException e) {
36             e.printStackTrace();
37         }
38     }
39 }

转换流  convert--->字节-字符

打印当前系统的字符编码:

System.out.println(osw.getEncoding());

 1 package com.convert;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.OutputStreamWriter;
 7 import java.io.UnsupportedEncodingException;
 8 
 9 public class TestTranForm1 {
10     public static void main(String[] args) {
11         OutputStreamWriter osw = null;
12         try {
13             
14             osw = new OutputStreamWriter(new FileOutputStream("E:\\Java\\0801 流后传 线程\\ceshi.txt"));
15             osw.write("山东淄博");//写入文件
16             // 默认使用当前系统的字符编码
17             System.out.println(osw.getEncoding());
18             osw.close();
19             
20             // FileOutputStream加第二个参数true表示追加内容
21             osw = new OutputStreamWriter(new FileOutputStream("E:\\Java\\0801 流后传 线程\\ceshi.txt", true), "utf-8");//更改字符编码
22             osw.write("qwerttttt");
23             System.out.println(osw.getEncoding());
24             osw.close();
25             
26         } catch (FileNotFoundException e) {
27             e.printStackTrace();
28         } catch (UnsupportedEncodingException e) { 
29             e.printStackTrace();
30         } catch (IOException e) {
31             e.printStackTrace();
32         }
33         
34     }
35 }

阻塞式方法

获取输入的内容转换成大写,如果输入的 exit 退出

 1 package com.convert;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class TestTranForm2 {
 8     public static void main(String[] args) {
 9         try {
10             InputStreamReader isr = new InputStreamReader(System.in);//包一层字符流
11             BufferedReader br = new BufferedReader(isr);//在包一层缓冲字符流
12             String s = null;
13             
14             s = br.readLine();//从字符流读取一行,你写入的内容
15             
16             while(s != null) {
17                 if(s.equalsIgnoreCase("exit")) {//忽略大小写的相同
18                     break;
19                 }
20                 System.out.println(s.toUpperCase());//将字符串转换成大写在控制台输出
21                 s = br.readLine();//再次获取输入的内容
22             }
23             
24             br.close();
25             
26             // 阻塞式方法(同步方法---不输入就不能干别的)
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31 }

数据流--->八大数据类型

 1 package com.data;
 2 
 3 import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.DataInputStream;
 6 import java.io.DataOutputStream;
 7 import java.io.IOException;
 8 
 9 public class TestDataStream {
10     public static void main(String[] args) {
11         ByteArrayOutputStream baos = new ByteArrayOutputStream();//字节数组输出流
12         DataOutputStream dos = new DataOutputStream(baos);//数据处理流,这个流可以直接写入基础数据类型
13         try {
14             dos.writeDouble(Math.random());
15             dos.writeBoolean(true);
16             ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());//将输出流转换为字节数组
17             System.out.println(bais.available());//里面包含的所有数据的长度
18             DataInputStream dis = new DataInputStream(bais);
19             /*
20              * 先进先出---队列
21              * 先进后出---栈
22              */
23             System.out.println(dis.readDouble());//数据流可以直接读取基本数据类型
24             System.out.println(dis.readBoolean());
25             dos.close();
26             dis.close();
27         } catch (IOException e) {
28             // TODO Auto-generated catch block
29             e.printStackTrace();
30         }
31     }
32 }

print流  打印流--->System.out.println();

 1 package com.print;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.PrintStream;
 6 
 7 public class TestPrintStream1 {
 8     public static void main(String[] args) {
 9         PrintStream ps = null;//打印流
10         
11         try {
12             FileOutputStream fos = new FileOutputStream("e:\\go\\testprint.txt");//文件字节输出流
13             ps = new PrintStream(fos);
14         } catch (FileNotFoundException e) {
15             e.printStackTrace();
16         }
17         
18         if(ps != null) {
19             // 设置默认的输出对象
20             System.setOut(ps);
21         }
22         
23         for(char c = 0;c<=60000;c++) {//输出6万个字符
24             System.out.print(c);
25             if(c % 100 == 0) {//输出到文件,不是控制台
26                 System.out.println();
27             }
28         }
29     }
30 }

定义方法,读取并打印文件

 1 package com.print;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileReader;
 6 import java.io.IOException;
 7 import java.io.PrintStream;
 8 
 9 public class TestPrintStream2 {
10     public static void main(String[] args) {
11         String fileName = "e:\\go\\file.txt";
12         
13         list(fileName, System.out);
14     }
15 
16     private static void list(String fileName, PrintStream ps) {
17         try {
18             BufferedReader br = new BufferedReader(new FileReader(fileName));//读取文件
19             String s = null;
20             
21             while((s = br.readLine()) != null) {
22                 ps.println(s);//读取并打印
23             }
24             br.close();
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             ps.println("无法读取文件 !");
29             e.printStackTrace();
30         }
31     }
32 }

模拟日志效果

输入内容,打印,并用分割线分开,最后打印当前日期

 1 package com.print;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.PrintWriter;
 8 import java.util.Date;
 9 
10 public class TestPrintStream3 {
11 
12     public static void main(String[] args) {
13         String s = null;
14         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//字节流转换字符流
15         
16         PrintWriter pwLog;
17         try {
18             FileWriter fw = new FileWriter("e:\\Java\\Ceshi-stream.log", true);//输出流的位置追加内容
19             pwLog = new PrintWriter(fw);
20             while((s = br.readLine()) != null) {//获取输入
21                 if(s.equalsIgnoreCase("exit")) {
22                     break;
23                 }
24                 System.out.println(s.toUpperCase());//打印到控制台大写
25                 pwLog.println("---------------------");//打印到文件分割线
26                 pwLog.println(s.toUpperCase());//打印到文件大写
27                 pwLog.flush();
28             }
29             pwLog.println("========== " + new Date() + " ===================");//结束后打印当前日期
30             pwLog.flush();
31             pwLog.close();
32         } catch (IOException e) {
33             e.printStackTrace();
34         }
35         
36         
37     }
38 
39 }

Object流

 1 package com.object;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.ObjectInputStream;
 8 import java.io.ObjectOutputStream;
 9 import java.io.Serializable;
10 
11 public class TestObjectStream {
12     public static void main(String[] args) {
13         try {
14             Test t = new Test();//实例化,自定义的类
15             t.i += 5;
16             FileOutputStream fos = new FileOutputStream("E:\\Java\\0801 流后传 线程\\ceshi.txt");//定义输出位置
17             ObjectOutputStream oos = new ObjectOutputStream(fos);//对象处理流包起来
18             oos.writeObject(t);//将对象写入到文件
19             oos.flush();
20             oos.close();
21             
22             FileInputStream fis = new FileInputStream("E:\\Java\\0801 流后传 线程\\ceshi.txt");//将文件读出来
23             ObjectInputStream ois = new ObjectInputStream(fis);
24             Test tread = (Test)ois.readObject();
25             System.out.println(tread);
26             ois.close();
27         } catch (FileNotFoundException e) {
28             e.printStackTrace();
29         } catch (ClassNotFoundException e) {
30             e.printStackTrace();
31         } catch (IOException e) {
32             e.printStackTrace();
33         }
34     }
35 }
36 
37 // Serializable--标记型接口, 没有实际的方法, 知识用来表示这个类可以被序列化
38 class Test implements Serializable {
39     
40     private static final long serialVersionUID = 1L;
41     
42     String name = "hanqi";
43     int i = 3;
44     int j = 15;
45     transient double d = 12.345; // 透明的, 表示这个属性在写入流的时候不予考虑
46         
47     
48     @Override
49     public String toString() {
50         return "Test [name=" + name + ", i=" + i + ", j=" + j + ", d=" + d + "]";
51     }
52 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档