java中IO流的使用(字节流的读入,复制文件,图片,视频)

java中字节流与字节缓冲流 

java中字节缓冲流 

import java.io.*;

public class IOshiping {
    public static void main(String[] args) throws IOException {
        //记录开始的时间
        long startTime = System.currentTimeMillis();
        //复制视频
        method();
        //记录结束的时间
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时"+(endTime-startTime)+"毫秒");
    }
    //字节缓冲流一次读入一个字节数组
    public static void method() throws IOException{
        //字节缓冲流创建字节输入流对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\jin\\Desktop\\Video_2019-07-17_113953_Trim.mp4"));
        //字节缓冲流创建字节输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\javaideacode\\day03\\shiping.mp4"));
        byte[] bys = new byte[1024];
        int len;
        while ((len = bis.read(bys))!=-1){
            bos.write(bys,0,len);
        }
        bos.close();
        bis.close();
    }
}

输出:

字节流复制图片

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

public class IOpicture {
    public static void main(String[] args) throws IOException {
        //时刻记住使用IO流是需要抛出异常的
        //创建字节输入流对象
        FileInputStream fis = new FileInputStream("C:\\Users\\jin\\Desktop\\preview.jpg");
        //创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("F:\\javaideacode\\day03\\mn.jpg");
        byte[] bys = new byte[1024];//这是按照一个字符数组读入
        int len;
        while((len = fis.read(bys))!=-1){//如果读完的话就会返回-1
            fos.write(bys,0,len);
        }
        fis.close();
        fos.close();
    }
}

 字节流创建文件,并在文件里面写入内容

import java.io.FileOutputStream;
import java.io.IOException;

public class IOliu {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //创建一个txt文件,并在文件里面写入文字
            fos = new FileOutputStream("F:\\javaideacode\\day03\\fos.txt");
            int t = 10;
            //在这个txt文件中写入10行hello
            while (t != 0) {
                t--;
                fos.write("hello".getBytes());
                fos.write("\n".getBytes());
            }
            //fos.write(bys,1,3);
            fos.close();
        }catch (IOException e){
             e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
原创文章 96 获赞 28 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43813140/article/details/102975989
今日推荐