Java文件操作--inputStream转为file

在玩爬虫的过程中,其中有一部分是下载视频,利用原生的HttpURLConnection获得获得inputStream之后,将输入流写入到本地文件中,形成mp4格式的视频文件,发现最初使用的方法特别慢,想找寻更好的方法,提升效率。

1.原始方法

//pathName就是文件保存的路径
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(pathName);
System.out.println("文件大约:"+(conn.getContentLength()/1024)+"K");
byte[] by = new byte[1024];
int len = 0;
while((len=bi.read(by))!=-1){
    fos.write(by,0,len);
}
fos.close();
bi.close();

这里在自己的机器上面进行网络请求进行的测试,一个5M左右的文件得3秒钟左右。

@Test
public void copyFile() throws FileNotFoundException, IOException{
/*		long startTime = System.currentTimeMillis();
		File file = new File("D:\\testDouyin.mp4");
		File otherFile = new File("D:\\dy.mp4");
		FileUtils.copyInputStreamToFile(new FileInputStream(file), otherFile);
		long endTime = System.currentTimeMillis();
		log.info("消耗时间:" + (endTime - startTime));*/
/*		
    File file = new File("D:\\testDouyin.mp4");
    long startTime = System.currentTimeMillis();
    BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
    FileOutputStream fos = new FileOutputStream("D:\\dy.mp4");
    byte[] by = new byte[2048];
    int len = 0;
    while((len=bi.read(by))!=-1){
        fos.write(by,0,len);
    }
    fos.close();
    bi.close();
	long endTime = System.currentTimeMillis();
	log.info("消耗时间:" + (endTime - startTime));
*/
/*
long startTime = System.currentTimeMillis();
File file = new File("D:\\testDouyin.mp4");
File otherFile = new File("D:\\dy.mp4");
Files.copy(new FileInputStream(file), otherFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
long endTime = System.currentTimeMillis();
log.info("消耗时间:" + (endTime - startTime));
*/
long startTime = System.currentTimeMillis();
		File file = new File("D:\\photocreator.jar");
		File otherFile = new File("D:\\ph.jar");
		FileInputStream inStream = new FileInputStream(file);
		FileOutputStream outStream = new FileOutputStream(otherFile);
		
		FileChannel in = inStream.getChannel();
		FileChannel out = outStream.getChannel();
		in.transferTo(0, in.size(), out);
		
		long endTime = System.currentTimeMillis();
		log.info("消耗时间:" + (endTime - startTime));
}

本机本地测试直接读取文件操作,使用commons IO的FileUtils时间为22毫秒;使用字节数组方式,5M的文件27毫秒;将byte[]调整为2048,操作时间为19毫秒。NIO的操作类时间26毫秒。又进行了大文件的测试,84M的文件,还是commons IO的FileUtils的速度稍快一些,当然这里的字节数组给的初始值较小,给更大的初始值,速度更快。

上面给出的代码中,最后一种方法是最快的,使用FileChannel进行文件的传输,这里使用的nio相关的知识。

猜你喜欢

转载自blog.csdn.net/m0_38129920/article/details/84028508