package com.onezero.web.service.impl;
import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
public class fileUtils {
public static void downFileToTarget(String origFile,String targetFile){
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//创建输入流 将源文件读取为流
fis = new FileInputStream(origFile);
//创建输出流 将流输入到目标文件
fos = new FileOutputStream(targetFile);
//获取通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//分配缓冲区 单位kb
ByteBuffer buffer = ByteBuffer.allocate(1024);
//将通道中数据存入缓冲区
while(inChannel.read(buffer)!=-1){
//Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded
//将缓存字节数组的指针设置为数组的开始序列即数组下标0。这样就可以从buffer开头,对该buffer进行遍历读取,读出当前缓冲区中的数据,不是按照缓冲区容量而是内容长度
buffer.flip();
//将缓冲区数据写入到输出通道中
outChannel.write(buffer);
//写完数据清除缓冲区
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outChannel != null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void downloadByNIO(String url, String filePath, String fileName) {
FileOutputStream fos = null;
ReadableByteChannel inChannel = null;
FileChannel outChannel = null;
try {
//获取数据流
InputStream in = new URL(url).openStream();
//创建输入流通道
inChannel = Channels.newChannel(in);
String targetFile=filePath+fileName;
fos = new FileOutputStream(targetFile);
outChannel = fos.getChannel();
//分配缓冲区 单位kb
ByteBuffer buffer = ByteBuffer.allocate(1024);
//将通道中数据存入缓冲区
while(inChannel.read(buffer)!=-1){
//Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded
//将缓存字节数组的指针设置为数组的开始序列即数组下标0。这样就可以从buffer开头,对该buffer进行遍历读取,读出当前缓冲区中的数据,不是按照缓冲区容量而是内容长度
buffer.flip();
//将缓冲区数据写入到输出通道中
outChannel.write(buffer);
//写完数据清除缓冲区
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outChannel != null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String origFile = "D:/java-download-001.pdf";
String targetFile = "D:/1.pdf";
downFileToTarget(origFile,targetFile);
String url = "https://www.onezero.cc/wp-content/uploads/2022/02/java-download-001.pdf";
String filePath = "D:/";
String fileName = "2.pdf";
downloadByNIO(url,filePath,fileName);
}
}