1.编写FileUtil类
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
public abstract class FileUtil {
/**
* 删除文件/文件夹(同时删除根目录)
* @param path
* @return boolean 如果出错返回false
*/
public static boolean delete(String path) {
File file = new File(path);
// 如果文件/文件夹不存在, 则不执行删除操作
if (!file.exists()) {
return true;
}
return clearFolder(path) && file.delete();
}
/**
* 清空文件夹(不删除根目录)
* @param path
* @return boolean 如果出错返回false
*/
public static boolean clearFolder(String path) {
File file = new File(path);
// 如果文件/文件夹不存在, 则不执行删除操作
if (!file.exists()) {
return true;
}
// 如果是文件
if (file.isFile()) {
return true;
}
// 如果是文件夹
File[] childFiles = file.listFiles();
for (File childFile : childFiles) {
if (childFile.isFile()) {
if (!childFile.delete()) {
return false;
}
} else {
if (!delete(childFile.getAbsolutePath())) {
return false;
}
}
}
return true;
}
/**
* 创建本地文件夹
* @param filePath
* @return
*/
public static boolean mkdirs(String folderPath) {
File folder = new File(folderPath);
if (folder.exists()) {
return folder.isDirectory();
} else {
return folder.mkdirs();
}
}
/**
* 将流复制到新文件
* @param in 基础文件流
* @param newFile 文件名(必须带有后缀)
* @return
*/
public static boolean copyFile(InputStream is, String newFile) {
BufferedInputStream bis = null;
OutputStream os = null;
BufferedOutputStream bos = null;
// 建立文件夹
if (!mkdirs(new File(newFile).getParent())) {
return false;
}
try {
// 获取输入流
bis = new BufferedInputStream(is);
os = new FileOutputStream(newFile);
bos = new BufferedOutputStream(os);
// 保存文件
int size = 0;
byte[] buf = new byte[1024 * 4];
while ((size = bis.read(buf)) != -1) {
bos.write(buf, 0, size);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(bos);
close(os);
close(bis);
close(is);
}
return true;
}
/**
* 关闭流
* @param o
*/
public static void close(Closeable... os) {
if (os != null) {
for (Closeable o : os) {
if (o != null) {
if (o instanceof Flushable) {
try {
((Flushable) o).flush();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 关闭流(不输出错误信息到控制台)
* @param o
*/
public static void closeQuiet(Closeable... os) {
if (os != null) {
for (Closeable o : os) {
if (o != null) {
if (o instanceof Flushable) {
try {
((Flushable) o).flush();
} catch (IOException e) {
}
}
try {
o.close();
} catch (IOException e) {
}
}
}
}
}
/**
* 将文件复制到新文件
* @param oldFile
* @param newFile(必须带有后缀)
* @return
*/
public static boolean copyFile(String oldFile, String newFile) {
if (!new File(oldFile).exists()) {
return false;
}
InputStream is = null;
try {
is = new FileInputStream(oldFile);
return copyFile(is, newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} finally {
close(is);
}
}
/**
* 复制文件夹
* @param oldFolder 源文件夹
* @param newFolder 目标文件夹
*/
public static boolean copyFolder(String oldFolder, String newFolder) {
// 检查旧文件夹是否存在
File old = new File(oldFolder);
if (!old.exists() || !old.isDirectory()) {
return true;
}
// 新建目标目录
mkdirs(newFolder);
// 复制源文件夹当前下的文件或目录
for (File file : old.listFiles()) {
String oldPath = file.getAbsolutePath();
String newPath = new File(newFolder, file.getName()).getAbsolutePath();
if (file.isFile()) {
if (!copyFile(oldPath, newPath)) {
delete(newPath);
return false;
}
} else {
if (!copyFolder(oldPath, newPath)) {
delete(newPath);
return false;
}
}
}
return true;
}
/**
* 移动文件到指定目录
* @param oldPath 如:c:/fqf.txt
* @param newPath 如:d:/fqf.txt
*/
public static boolean renameFile(String oldPath, String newPath) {
File file = new File(oldPath);
if (!file.exists()) {
return false;
}
return file.renameTo(new File(newPath));
}
/**
* 根据文件路径(含文件名及扩展名)获取文件名(含扩展名)
* @param fileNamePath
* @return String
*/
public static String getFileName(String fileNamePath) {
return new File(fileNamePath).getName();
}
/**
* 根据文件路径(含文件名及扩展名)获取根目录
* @param fileNamePath
* @return String
*/
public static String getRootDirctory(String fileNamePath) {
String[] fileNamePathArray = StringUtil.toArray(fileNamePath, "/");
return fileNamePathArray[0];
}
/**
* 根据文件路径(含文件名及扩展名)过滤扩展名
* @param fileNamePath
* @return String
*/
public static String getFilterExt(String fileNamePath) {
int lastIndex = fileNamePath.lastIndexOf('.');
if (lastIndex != -1)
return fileNamePath.substring(0, lastIndex);
else
return fileNamePath;
}
/**
* 根据文件路径(含文件名及扩展名)获取扩展名
* @param filename 文件名
* @return
*/
public static String getExtension(String filename) {
return getExtension(filename, "");
}
/**
* 根据文件路径(含文件名及扩展名)获取扩展名
* @param filename 文件名
* @param defExt 默认扩展名
* @return
*/
public static String getExtension(String filename, String defExt) {
if (filename != null && filename.length() > 0) {
int i = filename.lastIndexOf('.');
if (i > -1 && i < filename.length() - 1) {
return filename.substring(i + 1);
}
}
return defExt;
}
/**
* 过滤第一个文件夹
* @param filePath
* @return String
*/
public static String getFilterRootDir(String filePath) {
String[] folders = filePath.split("/");
int a = 1;
if (folders[0].trim().length() == 0) {
a = 2;
}
StringBuffer path = new StringBuffer();
for (int i = a; i < folders.length; i++) {
path.append("/").append(folders[i]);
}
return path.toString();
}
/**
* 将上传的文件转存到本地目录
* @param request 文件上传请求
* @param path 本地根路径
* @param unZip 是否解压zip文件
* @return
*//*
public static Map> transferToFile(MultipartRequest request, String path, boolean unZip) {
Map> map = new HashMap>();
Iterator inputNames = request.getFileNames();
while (inputNames.hasNext()) {
// input名称
String inputName = inputNames.next();
inputName = inputName.replaceAll("[^a-zA-Z0-9_]", "");
// 文件列表
List files = request.getFiles(inputName);
if (files != null && files.size() > 0) {
// 创建input同名文件夹
File folder = new File(path, inputName);
map.put(inputName, new ArrayList());
FileUtil.mkdirs(folder.getAbsolutePath());
// 解析input内所有文件
for (MultipartFile multipartFile : files) {
String fileName = multipartFile.getOriginalFilename();
// 非法文件名不进行解析
if (fileName != null && fileName.matches("[^\\\\/:\\*\\?\"<>\\|]+")) {
File file = new File(folder, fileName);
InputStream is = null;
try {
is = multipartFile.getInputStream();
copyFile(is, file.getAbsolutePath());
// 解压文件
} catch (Exception e) {
e.printStackTrace();
if (file.exists()) {
file.delete();
}
continue;
} finally {
close(is);
}
if (unZip && fileName.toLowerCase(Locale.ENGLISH).endsWith(".zip")) {
// 如果需要解压zip, 解压文件后将文件列表加入里面
String filePath = file.getAbsolutePath();
List list = ZipUtil.unZip(filePath, filePath.substring(0, filePath.length() - 4));
if (list != null) {
map.get(inputName).addAll(list);
}
} else {
map.get(inputName).add(file);
}
}
}
if (map.get(inputName).isEmpty()) {
map.remove(inputName);
FileUtil.delete(folder.getAbsolutePath());
}
}
}
return map;
}*/
/**
*
* @Title getFileMd5
* @Description 得到文件MD5
* @param filePath
* @return String
* @since 1.0.0
*//*
public static String getFileMd5(String filePath){
String md5Str = "";
InputStream is = null;
BufferedInputStream bis = null;
try {
//计算MD5值
is = new FileInputStream(filePath);
bis = new BufferedInputStream(is);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[8192];
int length;
while ((length = bis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
md5Str = new String(Hex.encodeHex(md.digest()));
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
if(null != bis){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return md5Str;
}
*/
/**
* 将字符串保存为文件
* @param str 字符串
* @param newPath 新文件全路径
*/
public static long saveString2File(String str, String newPath,String charsetName) {
OutputStreamWriter out = null;
long fileSize = str.length();;
try {
File f = new File(newPath);
out = new OutputStreamWriter(new FileOutputStream(f),charsetName);
out.write(str.toCharArray());
out.flush();
out.close();
}catch(IOException e){
e.printStackTrace();
}finally{
try {
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return fileSize;
}
//文件头信息
public static Map<String,String> fileHeaderInformation = null;
/**
*
* @Title getFileHeaderInformation
* @Description 得到文件的头信息
* @param extensionName
* @return String
* @since 1.0.0
*/
public static String getFileHeaderInformation(String extensionName){
if(fileHeaderInformation==null){
fileHeaderInformation = new HashMap<String,String>();
fileHeaderInformation.put("jpeg", "FFD8FF");
fileHeaderInformation.put("jpg", "FFD8FF");
fileHeaderInformation.put("png", "89504E47");
fileHeaderInformation.put("gif", "47494638");
fileHeaderInformation.put("tiff", "49492A00");
fileHeaderInformation.put("bmp", "424D");
fileHeaderInformation.put("dwg", "41433130");
fileHeaderInformation.put("psd", "38425053");
fileHeaderInformation.put("rtf", "7B5C727466");
fileHeaderInformation.put("xml", "3C3F786D6C");
fileHeaderInformation.put("html", "68746D6C3E");
fileHeaderInformation.put("eml", "44656C69766572792D646174653A");
fileHeaderInformation.put("dbx", "CFAD12FEC5FD746F");
fileHeaderInformation.put("pst", "2142444E");
fileHeaderInformation.put("xls", "D0CF11E0");
fileHeaderInformation.put("doc", "D0CF11E0");
fileHeaderInformation.put("xlsx", "D0CF11E0");
fileHeaderInformation.put("docx", "D0CF11E0");
fileHeaderInformation.put("mdb", "5374616E64617264204A");
fileHeaderInformation.put("wpd", "FF575043");
fileHeaderInformation.put("pdf", "255044462D312E");
fileHeaderInformation.put("qdf", "AC9EBD8F");
fileHeaderInformation.put("pwl", "E3828596");
fileHeaderInformation.put("zip", "504B0304");
fileHeaderInformation.put("rar", "52617221");
fileHeaderInformation.put("ram", "2E7261FD");
fileHeaderInformation.put("rm", "2E524D46");
fileHeaderInformation.put("wav", "57415645");
fileHeaderInformation.put("avi", "41564920");
fileHeaderInformation.put("mpg", "000001BA");
fileHeaderInformation.put("mpeg", "000001B3");
fileHeaderInformation.put("mov", "6D6F6F76");
fileHeaderInformation.put("asf", "3026B2758E66CF11");
fileHeaderInformation.put("mid", "4D546864");
}
if(extensionName==null){
return "";
} else {
String s = fileHeaderInformation.get(extensionName.toLowerCase());
return s==null?"":s;
}
}
}
2.编写ZipUtil类
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
public class ZipUtil {
/**
* 压缩文件
* @param iterator 源文件枚举
* @param zipFile 压缩文件路径
* @return
*/
public static boolean zip(ZipFileIterator iterator, String zipFile) {
OutputStream os = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
try {
os = new FileOutputStream(zipFile);
bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);
zos.setEncoding("GBK");
int length;
byte[] buf = new byte[1024 * 4];
while (iterator.next()) {
InputStream in = null;
BufferedInputStream bin = null;
try {
String fileName = iterator.getFileName();
if (iterator.isFile()) {
// 写入文件内容
zos.putNextEntry(new ZipEntry(fileName));
in = iterator.getInputStream();
bin = new BufferedInputStream(in);
while ((length = bin.read(buf, 0, buf.length)) != -1) {
zos.write(buf, 0, length);
}
} else {
// 写入文件夹定义
if (!fileName.endsWith("\\") && !fileName.endsWith("/")) {
fileName += File.separator;
}
zos.putNextEntry(new ZipEntry(fileName));
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
FileUtil.close(bin);
FileUtil.close(in);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
FileUtil.close(zos);
FileUtil.close(bos);
FileUtil.close(os);
}
}
/**
* 压缩文件/文件夹
* @param sourceDir 源目录路径
* @param zipFile 压缩文件路径
*/
public static boolean zip(String sourceDir, String zipFile) {
ZipFileIterator iterator = ZipFileIterator.forFolder(sourceDir, true);
return zip(iterator, zipFile);
}
/**
* 压缩多个文件
* @param sourceFiles 源文件列表
* @param zipFile 压缩文件路径
* @return
*/
public static boolean zip(File[] sourceFiles, String zipFile) {
ZipFileIterator iterator = ZipFileIterator.forFiles(sourceFiles);
return zip(iterator, zipFile);
}
/**
* 解压文件
* @param zipFile 待压缩文件
* @param destDir 解压路径
*/
public static List<File> unZip(String zipFile, String destDir) {
return unZip(zipFile,destDir,null);
}
/**
* 解压文件
* @param zipFile 待压缩文件
* @param destDir 解压路径
*/
public static List<File> unZip(String zipFile, String destDir, String encoding) {
List<File> list = new ArrayList<File>();
// 目标路径格式标准化
destDir = new File(destDir).getAbsolutePath() + File.separator;
// 读取zip文件
ZipFile zipfile = null;
try {
if(encoding!=null)
zipfile = new ZipFile(zipFile,encoding);
else
zipfile = new ZipFile(zipFile);
@SuppressWarnings("rawtypes")
Enumeration enumeration = zipfile.getEntries();
while (enumeration.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enumeration.nextElement();
String destPath = new File(destDir, entry.getName()).getAbsolutePath();
// 验证文件路径合法, 只能解压到目标路径下
if (destPath.startsWith(destDir)) {
if (entry.isDirectory()) {
// 如果是文件夹, 生成此文件夹
FileUtil.mkdirs(destPath);
} else {
list.add(new File(destPath));
// 如果是文件, 生成此文件
InputStream is = null;
try {
is = zipfile.getInputStream(entry);
FileUtil.copyFile(is, destPath);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
FileUtil.close(is);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
/**
* 解压rar格式的压缩文件到指定目录下
* @param rarFile 压缩文件
* @param destDir 解压目录
* @return
*/
public static List<File> unRar(String rarFile, String destDir) {
List<File> list = new ArrayList<File>();
Archive a = null;
try {
File file = new File(rarFile);
String filename = file.getName().substring(0, file.getName().lastIndexOf("."));
File fileDest = new File(destDir,filename);
destDir = fileDest.getAbsolutePath();
a = new Archive(file);
FileHeader fh = null;
while ((fh = a.nextFileHeader()) != null) {
String fileName = fh.isUnicode() ? fh.getFileNameW().trim() : fh.getFileNameString().trim();
String destPath = new File(destDir, fileName).getAbsolutePath();
if (fh.isDirectory()) {
// 如果是文件夹, 生成此文件夹
FileUtil.mkdirs(destPath);
} else {
// 如果是文件, 生成此文件
if (destPath.startsWith(destDir)) {
list.add(new File(destPath));
}
FileUtil.mkdirs(new File(destPath).getParent());
OutputStream os = null;
try {
os = new FileOutputStream(destPath);
a.extractFile(fh, os);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
FileUtil.close(os);
}
}
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
FileUtil.close(a);
}
}
/**
* 解压rar格式的压缩文件到指定目录下
* @param rarFile 压缩文件
* @param destDir 解压目录
* @return
*/
public static boolean unRar2(String rarFile, String destDir) {
Archive a = null;
try {
a = new Archive(new File(rarFile));
FileHeader fh = null;
while ((fh = a.nextFileHeader()) != null) {
String fileName = fh.isUnicode() ? fh.getFileNameW().trim() : fh.getFileNameString().trim();
String destPath = new File(destDir, fileName).getAbsolutePath();
if (fh.isDirectory()) {
// 如果是文件夹, 生成此文件夹
FileUtil.mkdirs(destPath);
} else {
// 如果是文件, 生成此文件
FileUtil.mkdirs(new File(destPath).getParent());
OutputStream os = null;
try {
os = new FileOutputStream(destPath);
a.extractFile(fh, os);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
FileUtil.close(os);
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
FileUtil.close(a);
}
}
/**
* byte数组转换成16进制字符串
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 根据文件流读取真实类型
*
* @param is
* @return
*/
public static String getTypeByStream(FileInputStream is) {
byte[] b = new byte[4];
try {
is.read(b, 0, b.length);
} catch (IOException e) {
e.printStackTrace();
}
String type = bytesToHexString(b).toUpperCase();
if (type.contains("504B0304")) {
return "zip";
} else if (type.contains("52617221")) {
return "rar";
}
return type;
}
public static List<File> unZipOrRar(String sourceRar, String destDir) {
return unZipOrRar(sourceRar,destDir,null);
}
public static List<File> unZipOrRar(String sourceRar, String destDir, String encoding) {
FileInputStream is;
try {
is = new FileInputStream(sourceRar);
String type = getTypeByStream(is);
if (type.equals("rar")) {
return unRar(sourceRar, destDir);
} else {
return unZip(sourceRar, destDir ,encoding);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 压缩多个文件
* @param file 要压缩的文件名
* @param zipfile 生成的zip文件
* @return
* @throws Exception
*/
public static void zipFiles(File[] srcfile, File zipfile) {
ZipOutputStream out=null;
FileInputStream in =null;
byte[] buf = new byte[1024];
try {
out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.length; i++) {
in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.编写JsonToXml类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import com.pde.util.FileUtil;
import com.pde.util.ZipUtil;
import exercise.xml.XmlExercise;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
/**
* 读取压缩包里面的Json文件,并且将json文件转换为xml文件
* @author Administrator
*
*/
public class JsonToXml {
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
parseZip();
long time2 = System.currentTimeMillis();
int time = (int) ((time2 - time1));
System.out.println("执行了:"+time+"豪秒!");
}
/**
* 读取压缩包并解压
*/
public static void parseZip() {
//String rarPath = "D:/01/2019-04-记-9lht.rar";
String rarPath = "D:/01/2019-04-记-9lht3.zip";
String destPath = "D:/01/temp";
List<File> list = ZipUtil.unZipOrRar(rarPath, destPath,"GBK");
for (File file : list) {
if(file.getAbsolutePath().endsWith(".json")) {
String jsonStr = readJsonFile(file);
jsonToXml(jsonStr);
}
}
FileUtil.delete(destPath);
}
/**
* json转xml
* @param jsonStr
*/
public static void jsonToXml(String jsonStr) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
JSONObject obj = JSONObject.fromObject(jsonStr);
String xml = XmlExercise.json2xml(obj.toString());
System.out.println(xml);
}
/**
*读取json文件
*
*/
public static String readJsonFile(File jsonFile) {
String jsonStr = "";
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
注:若有问题欢迎留言