package com.yeshi.buwan.util;
|
|
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.OutputStream;
|
import java.net.MalformedURLException;
|
import java.net.URL;
|
import java.net.URLConnection;
|
import java.util.*;
|
|
import javax.persistence.Entity;
|
import javax.persistence.GeneratedValue;
|
import javax.persistence.Id;
|
import javax.servlet.http.HttpServletRequest;
|
|
import org.apache.commons.fileupload.FileItem;
|
import org.apache.commons.fileupload.FileUploadException;
|
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
|
import com.yeshi.buwan.domain.FileName;
|
import com.yeshi.buwan.service.imp.VideoManager;
|
|
//文件处理
|
@Entity
|
public class FileUtil {
|
public final static int TYPE_PICTURE_CLASS = 1;// 分类图标文件夹
|
public final static int TYPE_PICTURE_HOME_AD = 2;// 广告图片
|
public final static int TYPE_PICTURE_VIDEO = 3;// 视频图片文件
|
public final static int TYPE_PICTURE_STAR = 4;// 明星头像
|
@Id
|
@GeneratedValue
|
public final static int TYPE_VIDEO = 5;// 视频文件
|
public final static String PROJECT_NAME = "BuWan";
|
|
/**
|
* 上传头像
|
*
|
* @param type
|
* @param request
|
* @return
|
*/
|
public List<String> getFile(int type, HttpServletRequest request) throws Exception {
|
List<String> resltList = new ArrayList<String>();
|
DiskFileItemFactory factory = new DiskFileItemFactory();
|
// 获取文件需要上传到的路径
|
String path = request.getRealPath("/upload");
|
|
// 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
|
// 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
|
/**
|
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
|
* 格式的 然后再将其真正写到 对应目录的硬盘上
|
*/
|
factory.setRepository(new File(path));
|
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
|
factory.setSizeThreshold(1024 * 1024);
|
|
// 高水平的API文件上传处理
|
ServletFileUpload upload = new ServletFileUpload(factory);
|
|
try {
|
// 可以上传多个文件
|
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
|
|
for (FileItem item : list) {
|
// 获取表单的属性名字
|
String name = item.getFieldName();
|
|
// 如果获取的 表单信息是普通的 文本 信息
|
if (item.isFormField()) {
|
|
}
|
// 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
|
else {
|
/**
|
* 以下三步,主要获取 上传文件的名字
|
*/
|
// 获取路径名
|
String value = item.getName();
|
// 索引到最后一个反斜杠
|
int start = value.lastIndexOf("\\");
|
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
|
String filename = value.substring(start + 1);
|
|
request.setAttribute(name, filename);
|
|
File file = new File(path);
|
|
if (!file.exists())
|
file.mkdirs();
|
|
File f = new File(createFile(type, path), filename);
|
|
resltList.add(f.getPath().split("webapps")[1]);
|
|
OutputStream out = new FileOutputStream(f);
|
|
InputStream in = item.getInputStream();
|
|
int length = 0;
|
byte[] buf = new byte[1024];
|
|
LogUtil.i("获取上传文件的总共的容量:" + item.getSize());
|
|
// in.read(buf) 每次读到的数据存放在 buf 数组中
|
while ((length = in.read(buf)) != -1) {
|
// 在 buf 数组中 取出数据 写到 (输出流)磁盘上
|
out.write(buf, 0, length);
|
}
|
|
in.close();
|
out.close();
|
}
|
}
|
|
} catch (FileUploadException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
}
|
return resltList;
|
}
|
|
public Map<String, String> getTextAndFile(int type, HttpServletRequest request) throws Exception {
|
Map<String, String> map = new HashMap<String, String>();
|
DiskFileItemFactory factory = new DiskFileItemFactory();
|
|
// 获取文件需要上传到的路径
|
String path = request.getRealPath("/upload");
|
|
// 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
|
// 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
|
/**
|
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
|
* 格式的 然后再将其真正写到 对应目录的硬盘上
|
*/
|
factory.setRepository(new File(path));
|
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
|
factory.setSizeThreshold(1024 * 1024);
|
|
// 高水平的API文件上传处理
|
ServletFileUpload upload = new ServletFileUpload(factory);
|
upload.setHeaderEncoding("UTF-8");
|
|
// 可以上传多个文件
|
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
|
for (FileItem item : list) {
|
// 获取表单的属性名字
|
String name = item.getFieldName();
|
|
// 如果获取的 表单信息是普通的 文本 信息
|
if (item.isFormField()) {
|
// String value = new String(item.getString().getBytes(),
|
// "UTF-8");
|
map.put(name, item.getString("UTF-8"));
|
}
|
// 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
|
else {
|
/**
|
* 以下三步,主要获取 上传文件的名字
|
*/
|
// 获取路径名
|
String value = item.getName();
|
if (StringUtil.isNullOrEmpty(value))
|
continue;
|
// 索引到最后一个反斜杠
|
int start = value.lastIndexOf("\\");
|
// .需要转义
|
String end = value.split("\\.")[1];
|
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
|
String filename = "";
|
if (value.contains(".") && value.length() > 2) {
|
filename = System.currentTimeMillis() + (int) (Math.random() * 10000) + "." + end;
|
request.setAttribute(name, filename);
|
}
|
File file = new File(path);
|
|
if (!file.exists())
|
file.mkdirs();
|
|
String createFile = createFile(type, path);
|
File f = new File(createFile, filename);
|
|
String fileName = createFile.split(PROJECT_NAME)[1] + File.separator + filename;
|
fileName = fileName.replace("\\", "/");
|
map.put(name, fileName);
|
|
OutputStream out = new FileOutputStream(f);
|
|
InputStream in = item.getInputStream();
|
|
int length = 0;
|
byte[] buf = new byte[1024];
|
|
LogUtil.i("获取上传文件的总共的容量:" + item.getSize());
|
|
// in.read(buf) 每次读到的数据存放在 buf 数组中
|
while ((length = in.read(buf)) != -1) {
|
// 在 buf 数组中 取出数据 写到 (输出流)磁盘上
|
out.write(buf, 0, length);
|
}
|
|
in.close();
|
out.close();
|
}
|
}
|
|
return map;
|
}
|
|
// 创建文件夹
|
private String createFile(int type, String path) {
|
if (type == TYPE_PICTURE_CLASS)// 分类图片
|
{
|
File f = new File(path, "class");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
} else if (type == TYPE_PICTURE_HOME_AD)// 首页广告图片
|
{
|
File f = new File(path, "ad");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
} else if (type == TYPE_PICTURE_STAR)// 明星头像
|
{
|
File ff = new File(path, "star");
|
if (!ff.exists())
|
ff.mkdirs();
|
File f = new File(ff.getPath(), "picture");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
} else if (type == TYPE_PICTURE_VIDEO)// 视频封面
|
{
|
File ff = new File(path, "juhe");
|
if (!ff.exists())
|
ff.mkdirs();
|
File f = new File(ff.getPath(), "picture");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
} else if (type == TYPE_VIDEO)// 视频封面
|
{
|
File ff = new File(path, "juhe");
|
if (!ff.exists())
|
ff.mkdirs();
|
File f = new File(ff.getPath(), "juhe");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
}
|
return "";
|
|
}
|
|
public static String getAbsolutePathWithProjectName(HttpServletRequest request, String path) {
|
return "http://" + request.getLocalAddr() + ":" + request.getLocalPort() + path;
|
}
|
|
public static void downFile(String urlStr, String filePath) throws MalformedURLException {
|
// 下载网络文件
|
int bytesum = 0;
|
int byteread = 0;
|
|
URL url = new URL(urlStr);
|
|
try {
|
URLConnection conn = url.openConnection();
|
InputStream inStream = conn.getInputStream();
|
FileOutputStream fs = new FileOutputStream(filePath);
|
|
byte[] buffer = new byte[1204];
|
while ((byteread = inStream.read(buffer)) != -1) {
|
bytesum += byteread;
|
LogUtil.i(bytesum);
|
fs.write(buffer, 0, byteread);
|
}
|
} catch (FileNotFoundException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
// 复制文件
|
public static boolean copyFile(String fileFrom, String fileTo) {
|
try {
|
File f = new File(fileTo);
|
if (!f.exists())
|
f.createNewFile();
|
|
FileInputStream in = new java.io.FileInputStream(fileFrom);
|
FileOutputStream out = new FileOutputStream(fileTo);
|
byte[] bt = new byte[1024];
|
int count;
|
while ((count = in.read(bt)) > 0) {
|
out.write(bt, 0, count);
|
}
|
in.close();
|
out.close();
|
return true;
|
} catch (IOException ex) {
|
return false;
|
}
|
}
|
|
public static boolean save(String ht, String path) throws IOException {
|
try {
|
File f = new File(path);
|
if (!f.exists())
|
f.createNewFile();
|
FileWriter writer;
|
writer = new FileWriter(path);
|
writer.write(ht);
|
writer.flush();
|
writer.close();
|
return true;
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return false;
|
}
|
|
public static List<FileName> reNameFile(String dir, String path) {
|
if (dir.endsWith("/"))
|
dir = dir.substring(0, dir.length() - 1);
|
VideoManager manager = new VideoManager();
|
List<FileName> list = new ArrayList<FileName>();
|
if (!StringUtil.isNullOrEmpty(dir))
|
if (StringUtil.isNullOrEmpty(path)) {// 获取文件夹下面的所有文件
|
File f = new File(dir);
|
File[] fileList = f.listFiles();
|
if (fileList.length > 0) {
|
String[] sts = fileList[0].getPath().split("\\.");
|
|
for (int i = 0; i < fileList.length; i++) {
|
String[] files = fileList[i].getPath().split("/");
|
FileName name = new FileName();
|
name.setNewName(
|
dir + "/" + manager.getVideoPathName(sts[sts.length - 1], files[files.length - 1]));
|
name.setOldName(files[files.length - 1]);
|
list.add(name);
|
fileList[i].renameTo(new File(list.get(i).getNewName()));
|
LogUtil.i(name.getOldName());
|
LogUtil.i(name.getNewName());
|
}
|
}
|
} else {// 获取某一个文件
|
String[] sts = path.split("\\.");
|
String newPath = dir + "/" + manager.getVideoPathName(sts[sts.length - 1], path);
|
new File(dir + "/" + path).renameTo(new File(newPath));
|
FileName name = new FileName();
|
name.setNewName(newPath);
|
name.setOldName(path);
|
list.add(name);
|
}
|
return list;
|
}
|
|
public static List<String> readText(String filepath) throws IOException {
|
List<String> list = new ArrayList<String>();
|
// String path = "C:/Users/Administrator/Desktop/乐视云/1234.txt";// 相对路径
|
File filename = new File(filepath);
|
BufferedReader bufread = new BufferedReader(new FileReader(filename));
|
String read;
|
while ((read = bufread.readLine()) != null) {
|
LogUtil.i(read);
|
list.add(read);
|
// readStr = (readStr + read);
|
}
|
// LogUtil.i("读取配置文件信息:" + readStr);
|
return list;
|
}
|
|
public static String readTxt(String filepath) throws IOException {
|
String result = "";
|
File filename = new File(filepath);
|
BufferedReader bufread = new BufferedReader(new FileReader(filename));
|
String read;
|
while ((read = bufread.readLine()) != null) {
|
LogUtil.i(read);
|
result += read;
|
// readStr = (readStr + read);
|
}
|
// LogUtil.i("读取配置文件信息:" + readStr);
|
return result;
|
}
|
|
public static String saveAsFile(InputStream inputStream, String path) throws IOException {
|
if (!new File(path).exists()) {
|
new File(path).createNewFile();
|
}
|
|
FileOutputStream fileOut = new FileOutputStream(new File(path));
|
byte[] buf = new byte[1024 * 8];
|
while (true) {
|
int read = 0;
|
if (inputStream != null) {
|
read = inputStream.read(buf);
|
}
|
if (read == -1) {
|
break;
|
}
|
fileOut.write(buf, 0, read);
|
}
|
fileOut.close();
|
return path;
|
}
|
|
public static String getCacheDir() {
|
|
String os = System.getProperty("os.name");
|
if (os.toLowerCase().startsWith("win")) {
|
File f = new File("D:/cache");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
} else {
|
File f = new File("/usr/local/cache");
|
if (!f.exists())
|
f.mkdirs();
|
return f.getPath();
|
}
|
}
|
|
|
|
|
|
}
|