Java笔记----File类和IO流(二)

对于图片视频等文件用前面的字符流Reader和Writer是不行的,得用下面的字节流。

一、FileInputStream和FileOutputStream

四步走套路,直接上代码

@Test
    public void test(){
        FileInputStream fileinputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1.创建File类对象,指明读入写出文件
            File srcFile = new File("时间API.png");
            File destFile = new File("新时间API.png");
            //2.创建流对象
            fileinputStream = new FileInputStream(srcFile);
            fileOutputStream = new FileOutputStream(destFile);
            //3.数据的读入和写出
            byte[] bBuf = new byte[20];
            int len;
            while ((len = fileinputStream.read(bBuf))!=-1){
                fileOutputStream.write(bBuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流资源关闭
            if(fileinputStream!=null){
                try {
                    fileinputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
二、转换流InputStreamReader和OutputStreamReader

先来了解转换流的基本知识,包括字符集。转换流用起来的结构看上去像一根电线:铜线->胶皮->绝缘编织布,中间是一个流,外面包裹层的就是转换流。

 * 1.转换流:属于字符流
 * InputStreamReader:将一个字节的输入流转换为字符的输入流
 * OutputStreamwriter:将一个字符的输出流转换为字节的输出流
 *
 * 2.作用:提供字节流与字符流之间的转换
 *
 * 3.解码:字节、字节数组--->字符数组、字符串
 * 编码:字符数组、字符串--->字节、字节数组
 *
 * 4.字符集
 * ASCII:.美国标准信息交换码。用一个字节的7位可以表示。
 * IS08859-1:拉丁码表。欧洲码表用一个字节的8位表示。
 * GB2312:中国的中文编码表。最多两个字节编码所有字符
 * GBK:中国的中文编码表开级,融合了更多的中文文字符号。最多两个字节编码
 * Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字
 		   都用两个字节来表示,落地实施为UTF-816,现有32
 * UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
 *

@Test
    public void test1(){
        java.io.InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            //1.造文件,造流
            FileInputStream fis = new FileInputStream("三种建模方法对比和应用.txt");
            FileOutputStream fos = new FileOutputStream("三种建模方法对比和应用_gbk.txt");

            isr = new java.io.InputStreamReader(fis,"UTF-8");
            osw = new OutputStreamWriter(fos,"gbk");

            //2.读写过程
            char[] cbuf = new char[20];
            int len;
            while((len = isr.read(cbuf))!= -1){
                osw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭资源
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(osw!=null){
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

练练手:从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入"e"或者“exit"时,退出程序。

  • 方法一:使用Scanner实现,调用next()返回一个字符串
  • 方法二:使用System.in实现。System.in->转换流 ->BufferedReader的readLine()
public static void main(String[] args) {
        BufferedReader br = null;
        try {
            java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
            br = new BufferedReader(isr);
            while (true) {
                System.out.println("请输入字符串: ");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                    System.out.println("程序结束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
三、打印流 PrintStream和PrintWriter,提供了一系列的println()和print()

练练手:打印255个ASCII字符

@Test
    public void test2(){
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("PrintExer.txt"));
            //创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true) ;
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }
            for (int i = 0; i <= 255; i++) { //输出ASCII字符
                System. out . print((char) i);
                if(i%50==0){//每50个数据一行
                    System. out.println(); //换行
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(ps!=null){
                ps.close();
            }
        }
    }
四、对象流 ObjectInputStream和ObjectOutputStream
  1. 作用:用于存储和读取基本数据类型或对象的处理流。
    它的强大之处在于可以把Java中的对象从数据源中还原回来
  2. 要想一个Java类对象是可序列化的,需要满足相应的要求。见下面的Person类

Person类需要满足以下要求,方可序列化

  • 需要实现接口:Serializable
  • 当前类提供一一个全局常量: serialVersionUID
  • 除了当前Person类需要实现Serializable接口之外, 还必须保证其内部所有属性
  • 也必须是可序列化的。(默认情况下, 基本数据类型可序列化)
  • ObjectInputStream和ObjectOutputStream不能序列化static和transient修饰的成员变量
public class Person implements Serializable {

    public static final long serialVersionUID = 4758912231L;

    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class ObjectInputOutputStream {
    /*
    序列化过程:将内存中的Java对象保存到磁盘中或通过网络传输出去
    使用ObjectOutputStream实现
     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("hah.dat"));

            oos.writeObject(new String("我喜欢你"));
            oos.flush();

            oos.writeObject(new Person("小明",22));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    反序列化:将磁盘文件中的对象还原为内存中的一个Java对象
    使用ObjectInputStream
     */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("hah.dat"));

            Object o = ois.readObject();
            String str = (String) o;

            Person p = (Person) ois.readObject();

            System.out.println(str);
            System.out.println(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值