FileTools
阳狐若
2023-12-01
package cn.net.zzfz.center.common.util;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 文件上传
* @author song
*
*/
public class FileTools {
private static Logger logger = LoggerFactory.getLogger(FileTools.class);
public static void uploadFile(File file, String toFilePath) throws FileNotFoundException, Exception {
InputStream is = null;
BufferedOutputStream os = null;
if(!new File(toFilePath).exists()){
String path = StringUtils.substringBeforeLast(toFilePath, "/");
boolean b = new File(path).mkdirs();
if(!b){
logger.error("{msg:'上传文件时,创建失败,无权限创建目录, 文件名:[{}]', toFilePath:{}, time:{}}",file.getName(),toFilePath,DateJodaTimeUtils.getNowTime());
throw new Exception("上传文件时,创建失败,无权限创建目录");
}
}
try {
is = new FileInputStream(file);
os = new BufferedOutputStream(new FileOutputStream(toFilePath));
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException fnfe) {
throw fnfe;
} catch (IOException ioe) {
throw ioe;
} finally {
if (os != null)
os.close();
if (is != null)
is.close();
}
}
public static void uploadFile(InputStream fis, String toFilePath) throws FileNotFoundException, Exception {
InputStream is = null;
BufferedOutputStream os = null;
String path = StringUtils.substringBeforeLast(toFilePath, "/");
if(!new File(path).exists()){
boolean b = new File(path).mkdirs();
if(!b){
logger.error("{msg:'上传文件时,创建失败,无权限创建目录', toFilePath:{}, time:{}}",toFilePath,DateJodaTimeUtils.getNowTime());
throw new Exception("上传文件时,创建失败,无权限创建目录");
}
}
try {
is = fis;
os = new BufferedOutputStream(new FileOutputStream(toFilePath));
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException fnfe) {
throw fnfe;
} catch (IOException ioe) {
throw ioe;
} finally {
if (os != null)
os.close();
if (is != null)
is.close();
}
}
public static String getFileContent(String filePath) throws Exception {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
StringBuffer sb = new StringBuffer();
String temp = null;
while ((temp = in.readLine()) != null) {
if (temp.trim().length() > 0) {
sb.append(temp).append("\n");
}
}
return sb.toString();
} finally {
if (in != null)
in.close();
}
}
public static List<String> getFileContentList(String filePath) throws Exception {
BufferedReader in = null;
List<String> l = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(filePath));
String temp = null;
while ((temp = in.readLine()) != null) {
if (temp.trim().length() > 0) {
l.add(temp);
}
}
return l;
} finally {
if (in != null)
in.close();
}
}
public static String getFileContent(File file) throws Exception {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String temp = null;
while ((temp = in.readLine()) != null) {
sb.append(temp).append("\r\n");
}
return sb.toString();
} finally {
if (in != null)
in.close();
}
}
public static String getFileContent(File file, String charset) throws Exception {
BufferedReader in = null;
try {
InputStream is = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(is, charset);
in = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String temp = null;
while ((temp = in.readLine()) != null) {
sb.append(temp).append("\r\n");
}
return sb.toString();
} finally {
if (in != null)
in.close();
}
}
public static void setFileContent(String content, String filePath) throws Exception {
FileWriter fw = null;
try {
fw = new FileWriter(filePath);
fw.write(content);
} finally {
if (fw != null) {
fw.close();
}
}
}
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
return file.delete();
}
public static boolean mkdir(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return file.mkdir();
}
return true;
}
public static boolean mkdirs(String filePath) {
File file = new File(filePath);
return file.mkdirs();
}
public static void deleteDirectory(File dir) throws IOException {
if ((dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " + dir + " is not a directory. ");
}
File[] entries = dir.listFiles();
for (int i = 0; i < entries.length; i++) {
if (entries[i].isDirectory()) {
deleteDirectory(entries[i]);
} else {
if (!entries[i].delete()) {
throw new IllegalArgumentException(entries[i] + " can not be delete. ");
}
;
}
}
if (!dir.delete()) {
throw new IllegalArgumentException("Argument " + dir + " can not be delete. ");
}
}
public static void buildHtml(String target_url, String save_path) throws FileNotFoundException, IOException {
try {
URL openurl = new URL(target_url);
URLConnection urlConn = openurl.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
urlConn.connect();
InputStream is = urlConn.getInputStream();
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(save_path));
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
is.close();
os = null;
is = null;
} catch (FileNotFoundException fnfe) {
throw fnfe;
} catch (IOException ioe) {
throw ioe;
}
}
public static String getFileExt(String name) {
if (name.lastIndexOf(".") == -1) {
return "";
}
return name.substring(name.lastIndexOf(".") + 1, name.length());
}
public static String getFileName(String name) {
if (name.lastIndexOf(".") == -1) {
return "";
}
return name.substring(0, name.lastIndexOf("."));
}
public static String getRandomFileName(String postfix) {
java.util.Date dt = new java.util.Date(System.currentTimeMillis());
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = fmt.format(dt);
fileName = fileName + "." + postfix; //extension, you can change it.
return fileName;
}
}