1. 使用场景,某个文件服务器里面保存了某个图片或者pdf文件,通过url的形式传输到自己这边,然后需要将url承载的文件保存到自己的电脑(服务器)里面。
2. 如果url自带文件名或者文件名加文件后缀那就是最方便的,获取文件名和后缀的时候就从urlAddress.substring来获取,反之这里工具用的是url不带文件名和后缀,需要自己传入destinationDir,并且我这里将文件后缀名字写死了.jpg,可以写一个灵活的后缀
3. 工具类的入口是fileDownload方法urlAddress大致长成"http://www.baidu.com/xxxxxxx"
destinationDir大致为"/User/file/xxx.jpg"
4.工具是灵活的传入的参数也是灵活的,可根据自己的需要修改
@UtilityClass
@Slf4j
public class FileUtil {
/**
* SIZE
*/
private final int size = 1024;
/**
* File url
*
* @param urlAddress url address
* @param localFileName local file name
* @param destinationDir destination dir
*/
public static void fileUrl(String urlAddress, String localFileName, String destinationDir) {
OutputStream outputStream = null;
URLConnection urlConnection = null;
InputStream inputStream = null;
try {
URL url = new URL(urlAddress);
outputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(destinationDir + "\\" + localFileName + ".jpg")));
urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
byte[] buf = new byte[size];
int byteRead, byteWritten = 0;
while ((byteRead = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, byteRead);
outputStream.flush();
byteWritten += byteRead;
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
inputStream.close();
outputStream.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
/**
* File download
*
* @param urlAddress url address
* @param destinationDir destination dir
*/
public static void fileDownload(String urlAddress, String destinationDir) {
int slashIndex = destinationDir.lastIndexOf('/');
int periodIndex = destinationDir.lastIndexOf('.');
String fileName = destinationDir.substring(slashIndex + 1, periodIndex);
if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < urlAddress.length() - 1) {
fileUrl(urlAddress, fileName, destinationDir);
} else {
System.err.println("path or file name.");
}
}
}