文件下载,上传,删除等操作工具类
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
public class FileUtil {
private FileUtil() {
}
public static byte[] getBytesByFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
if (!targetFile.mkdirs()) {
throw new IOException();
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath + "/" + fileName);
out.write(file);
out.flush();
} catch (IOException e) {
throw new IOException();
} finally {
if (out != null) {
out.close();
}
}
}
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
}
return false;
}
public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
public static boolean deleteQuietly(String fileAddress) {
File file = new File(fileAddress);
if (file == null) {
return false;
} else {
try {
if (file.isDirectory()) {
}
} catch (Exception var3) {
;
}
try {
return file.delete();
} catch (Exception var2) {
return false;
}
}
}
public static void downloadLocal(HttpServletResponse response, String filePath,String encode) {
response.setContentType("text/html;charset=" + encode);
try {
InputStream inStream = new FileInputStream(filePath);
File file = new File(filePath);
String fileName = file.getName();
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(encode), "ISO8859-1") + "\"");
byte[] b = new byte[100];
int len;
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}