Java基础语法 IO流核心(读进来,写出去)

Java基础语法 IO流核心(读进来,写出去)

一、IO流存在的意义
  • 解决设备与设备之间的数据传输问题,比如:硬盘------->内存 内存-------->硬盘。

  • 计算机进行网络数据传输,文件读写,用户输入和打印的时候都需要用到IO流。

二、IO流分类

Java IO流共涉及40多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧密的联系,Java IO流的40多个类都是从如下4个抽象类基类中派生出来的。
InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。
OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。
注:它们都是一些抽象基类,无法直接创建实例。

image-20210426143905196

三、字符流和字节流

字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。 字节流和字符流的区别:

  • 读写单位不同:字节流以字节(8 bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。
  • 处理对象不同:字节流能处理所有类型的数据(如图片、avi 等),而字符流只能处理字符类型的数据。

结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

四、输入流和输出流

对输入流只能进行读操作,对输出流只能进行写操作,程序中需要根据待传输数据的不同特性而使用不同的流。

五、IO流常用读写操作
  1. 使用字符流复制文件

    //使用字符流复制文件
    public class Test{
    public static void main(String[] args) throws IOException  {
        try(BufferedReader br = new BufferedReader(new FileReader("E:\\Test1.txt")); //通过文件缓冲流读文件
            BufferedWriter bw   = new BufferedWriter(new FileWriter("E:\\Test2.txt"))) {
            char[] ch = new char[100];
            int len;
            while((len = br.read(ch))!=-1) {//以一个字符数组为中介存储或者读写东西,也有防止数组浪费的好处
                bw.write(ch);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      }
    }
    
  2. 字节流复制数据

    public class Test{
    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\Test3.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\Test4.jpg"));
        byte[] b = new byte[1024];
        int len;
        while((len = bis.read(b))!=-1) {//字符流通过字符数组,字节流当然通过字节数组
            bos.write(b);
            bos.flush();
        }
        bos.close();
        bis.close();
    }
    
  3. 字符和字节的转换

    public class Test{
        public static void main(String[] args) {
            //字符串   a  c  v 
            String str1 = 12 + "";
            //String str2 = 'a' + "";
            //将字符串转换成字节数组,可以输出一下更好理解流的本质
            byte[] bytes = "abc".getBytes();
            for (int j = 0; j < bytes.length; j++) {
                System.out.println(bytes[j]);
            }
            //有参构造  将字节数组 编程 字符串
            String str = new String(bytes);
            //重写了toString  打印字符串的内容
            System.out.println(str.toString());
      }
    }
    
  4. 查找后缀名是 .txt 的文件

    public class Test{
    public static void main(String[] args) {
        getDir("F:\\", ".txt");
    }
    public static void getDir(String path,String latter) {
    	File f = new File(path);
    	if(f.isFile()) { //如果是文件的话就可以输出路径
        	if(f.getName().endsWith(latter)) {
            	System.out.println(f.getAbsolutePath());
        	}
    	}
    	else {
        	File[] list = f.listFiles();//不是文件的话必须得深入文件夹去查看
        	if(f.length()>0&&list!=null) {
            	for (File file : list) {//遍历文件夹中的东西
                	getDir(file.getAbsolutePath(), latter);
            	}
        	}
    	}
      }
    }
    
  5. 删除某一个文件 (和查找相似)

    public class Test{
    public static void main(String[] args) throws IOException {
        removeDir("F:\\practice");
    }
    public static void removeDir(String path) throws IOException {
        File file = new File(path);
        if(file.isFile()) {
        	file.delete();
        }
        else {
            File[] listFiles = file.listFiles();
            for (File file2 : listFiles) {
                removeDir(file2.getAbsolutePath());
            }
            file.delete();
        }
      }
    }
    
  6. 一个项目中的实例某一块运用

    public static void main(String[] args) {
        List<ShoppingBean> list = new ArrayList<>();
        try(BufferedReader br = new BufferedReader(new FileReader("D:\\a.txt"));) {
            String str;
            while((str=br.readLine())!=null) { //可以一行一行读取
                String[] split = str.split(",");
                 int id = Integer.parseInt(split[0]);
                 String name = split[1];
                 double price = Double.parseDouble(split[2]);
                 int number = Integer.parseInt(split[3]);
                 ShoppingBean bean = new ShoppingBean();
                 bean.set(id, name, price, number);
                 list.add(bean);
    		}
    	}
    }
    
  7. 解决乱码问题,看源代码是什么编码,使用包装类解决

    public void downLoad() throws IllegalArgumentException, IOException {
            FSDataInputStream input = fs.open(new Path("/upload.txt"));
            BufferedReader  br = new BufferedReader(new InputStreamReader(input,"utf-8")); //使用包装类修改编码
             BufferedWriter bw = new BufferedWriter(new FileWriter("e:/upload.txt"));
             String str = null;
             while((str = br.readLine())!= null) {
                 bw.write(str);
             }
             bw.close();
             br.close();
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

很萌の萌新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值