javaee学习日记之java基础之I/O流

文件类:
File
(操作文件或文件夹的类)


import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileTool {
    public static void main(String[] args) {
        /* 编写一个能输出当前目录下,所有扩展名为“.java”的文件 */
        try {
            getjava();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void getjava() throws IOException {
        File file = new File("D:/myeclipse/IO/src/cn/heci/domin");//指定目录

        System.out.println(file.getCanonicalPath());//当前目录
        String[] lis = file.getCanonicalFile().list((die, src) -> src.matches("\\w*\\.java"));//文件列表//jdk8新特性(Lambda 表达式)
        for (String s : lis) {
            System.out.println(s);//遍历
        }

    }
}

输出流
OutputStream(接口)
子类
FileOutputStream(节点流)(当指定文件不存在时(会创建))


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Tow {
    public static void main(String[] args) {
        /*
         * 使用FileOutputStream类的对象向文件写入数据 (1)、使用覆盖写的方式,向文件fos.dat写入一首诗。
         * (2)、在(1)的基础上,使用追加写的方式,再写入“我爱Java”。
         */
        setFile();
    }

    public static void setFile() {
        File file = new File("D:\\fos.dat");//文件类
        FileOutputStream fos = null;//创建输出流
        try {
            fos = new FileOutputStream(file);//设定输出文件路径
            byte[] b = "春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。".getBytes();//设定写入数据
            fos.write(b);//写入
            byte[] b2 = "我爱java".getBytes();//追写数据
            fos.write(b2);//追写
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fos.close();//释放资源
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

输入流
InputStream(接口)
子类
FileInputStream(节点流)


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Test {
    public static void main(String[] args) {
        //读取D:\\fos.dat的文件内容
        InputStream is = null;
        try {
            is = new FileInputStream("D:\\fos.dat");//设定读取文件的路径
            byte[] b = new byte[1024];//一次读取1024个字节
            int len = 0;
            while ((len = is.read(b)) != -1) {//读取后是否为空
                System.out.println(new String(b, 0, len));//输出从0-len的b数组
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                is.close();//释放资源
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

BufferedInputStream(缓冲输入流)(处理流)
BufferedOutputStream(缓冲输出流)(处理流)


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Test {
    public static void main(String[] args) {
        try (OutputStream bo = new BufferedOutputStream(new FileOutputStream("D:\\fos_copy3.dat"));
                InputStream bi = new BufferedInputStream(new FileInputStream("D:\\fos.dat"));) {
            byte[] b = new byte[1024];
            int x = 0;
            while ((x = bi.read(b)) != -1) {
                bo.write(b,0,x);
            }
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

使用编码写读文件

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Test {
    public static void main(String[] args) {
        try (OutputStream fos = new FileOutputStream("D:\\utf8.dat");
                InputStream fis = new FileInputStream("D:\\utf8.dat");) {
            byte[] b = "床前明月光".getBytes("utf-8");
            fos.write(b);
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = fis.read(bs)) != -1) {
                System.out.println(new String(bs, 0, len, "utf-8"));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

RandomAccessFile(一个特殊的流(能读能写))

import java.io.IOException;
import java.io.RandomAccessFile;

public class Test {
    public static void main(String[] args) {
        //在当前目录下创建raf.dat,写入,并读取
        try (RandomAccessFile raf = new RandomAccessFile("raf.dat", "rw");) {//创建读写流,赋予读写权限
            raf.seek(0);//指针设为开始
            raf.write(1);//写入1
            raf.seek(0);//指针设为开始
            System.out.println(raf.read());//读取1
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

序列化和反序列化

import java.io.Serializable;

public class Emp implements Serializable{//序列化对象要实现Serializable
    private static final long serialVersionUID = 1L;
    String name;
    int age;
    String gender;
    int salary;
    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;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }

}


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Sex {
    public static void main(String[] args) {
        /*
         * 实现存储Emp的序列化和反序列化 (1)使用属性name、age、gender、salary为[“张三”,15,
         * “男”,4000]构造Emp类的对象。 (2)将第一步创建的Emp对象,序列化到文件emp.obj中
         * (3)将第二步序列化到emp.obj中的Emp对象,反序列化出来并输出到控制台
         */
        try {
            test();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }

    public static void test() throws FileNotFoundException, IOException, ClassNotFoundException {
        Emp emp = new Emp();
        emp.setAge(15);
        emp.setName("张三");
        emp.setSalary(4000);
        emp.setGender("男");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("emp.obj"));//序列化
        oos.writeObject(emp);//写入emp.obj文件中

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("emp.obj"));//反序列化emp.obj文件
        Emp emp2 = (Emp) ois.readObject();//赋给对象
        System.out.println(emp2.getName()+" "+emp2.getAge()+" "+emp2.getGender()+" "+emp2.getSalary());//输出

        oos.close();//释放资源
        ois.close();//释放资源
    }
}

转换流
OutputStreamWriter:输出转换流
InputStreamReader:输入转换流
BufferedWriter:字符缓存输出流(处理流)
BufferedReader:字符缓存输入流(处理流)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Test {
    public static void main(String[] args) {
      try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/myeclipse/demo/jj.txt")));BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:/myeclipse/demo/raf.dat")))){
          String line = null; //读取一行
          while((line = br.readLine()) != null){//判断是否存在数据  
              bw.write(line,0,line.length());  //写入数据从0-length — 1
              bw.newLine();  //换行
              bw.flush();  //将数据刷新到文件中
          }  
      }catch(IOException e){
         e.printStackTrace(); 
      }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值