Java文件工具类
/**
* 读取项目根目录下的文件内容
* @author zg-bill
* @date 2020/9/15 16:03
* @param filePath 文件路径
* @return
**/
public static String readFile(String filePath){
StringBuffer content = new StringBuffer();
try(BufferedReader in = new BufferedReader(new FileReader(filePath))) {
String line = "";
while((line = in.readLine()) != null){
content.append(line);
}
}catch (Exception e){
log.error("文件读取失败",e);
}
return content.toString();
}
/***
* 获取文件后缀名
* @author zg-bill
* @date 2022/3/15 14:02
* @param fileUrl: 文件路径或者url
* @return: java.lang.String
**/
public static String getFileSuffixName(String fileUrl){
return fileUrl.substring(fileUrl.lastIndexOf(".")+1);
}
/***
* 通过url判断文件是否是期望的大小
* @author zg-bill
* @date 2022/3/15 15:35
* @param urlPath: 文件网络地址
* @param size: 大小(byte)
* @return: boolean
**/
public static boolean isExpectedSize(String urlPath,long size){
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000*5);
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
long fileLength = httpURLConnection.getContentLength();
if (fileLength <= size){
return true;
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/***
* 通过网络地址获取文件流
* @author zg-bill
* @date 2022/3/15 15:48
* @param urlPath:
* @return: java.io.InputStream
**/
public static InputStream getInputStreamByUrlPath(String urlPath){
InputStream inputStream = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000*5);
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 获取输入流
inputStream = httpURLConnection.getInputStream();
}catch (Exception e){
e.printStackTrace();
log.error("获取网络文件流失败【{}】",urlPath);
}
return inputStream;
}