Java入门需要了解(字节流-三十六)

测试代码很多都是写死的,实际使用中将其动态化即可

FileOutputStream 写入文件

 public static void testStreamWrite() throws IOException {
        //创建字节流输出对象
        FileOutputStream fileOutputStream = new FileOutputStream("byteStream.txt");
        //把内容直接写到了目的文件中
        fileOutputStream.write("abcd".getBytes());
		//关闭流对象
        fileOutputStream.close();
    }

FileInputStream 读取文件

 public static void testStreamRead() throws IOException {
        //创建字节流输入对象
        FileInputStream fileInputStream = new FileInputStream("byteStream.txt");
        //这里读取英文是没有问题的,但是如果是中文,则会出现乱码
        int ch=0;
        while((ch=fileInputStream.read())!=-1){
            System.out.println("ch = " + (char)ch);
        }
        fileInputStream.close();
    }

FileInputStream 读取文件byte[]

 public static void testStreamReadArr() throws IOException {
        //创建字节流输入对象
        FileInputStream fileInputStream = new FileInputStream("byteStream.txt");
        //这里读取英文是没有问题的,但是如果是中文,则会出现乱码
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            System.out.println("ch = " + new String(bytes,0,len));
        }
        fileInputStream.close();
    }

使用字节流复制文件(图片)

这样的复制文件的方式可以是任意格式的文件
复制文件时,千万不要读取一个字节写入一个字节,效率奇低

public static void copyFile() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("image.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("image_copy.jpg");
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            fileOutputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }

使用缓冲区复制文件(图片)

这样的复制文件的方式可以是任意格式的文件

public static void copyFile2() throws IOException {
		//定义文件输入流关联一个文件
        FileInputStream fileInputStream = new FileInputStream("image.jpg");
        //定义输入流缓冲区管理一个输入流对象
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        //定义一个输出流对象,关联一个文件
        FileOutputStream fileOutputStream = new FileOutputStream("image_copy.jpg");
        //定义一个输出流缓冲区,管理一个输出流对象
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        byte[] bytes = new byte[1024];
        int len = 0;
        //从输入流缓冲区中读取文件内容
        while ((len = bufferedInputStream.read(bytes)) != -1) {
        	//通过输出流缓冲区将读取的内容写入到输出流关联的文件中
            bufferedOutputStream.write(bytes,0,len);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值