/** * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.landtool.lanbase.common.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.servlet.http.HttpServletResponse; import com.landtool.lanbase.common.Constant; import com.landtool.lanbase.common.exception.LanbaseException; /** * @author lanbase * @Description: TODO(文件处理) * @date 2017-6-23 15:07 */ public class FileUtils { public static String getSuffix(String fileName) { if (fileName != null && fileName.contains(".")) { return fileName.substring(fileName.lastIndexOf(".")); } return null; } public static String removePrefix(String src, String prefix) { if (src != null && src.startsWith(prefix)) { return src.substring(prefix.length()); } return src; } public static String readString(File file) { ByteArrayOutputStream baos = null; FileInputStream fis = null; try { fis = new FileInputStream(file); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int len = 0; (len = fis.read(buffer)) > 0;) { baos.write(buffer, 0, len); } return new String(baos.toByteArray(), Constant.ENCODING_UTF_8); } catch (Exception e) { } finally { close(fis, baos); } return null; } public static void writeString(File file, String string) { FileOutputStream fos = null; try { fos = new FileOutputStream(file, false); fos.write(string.getBytes(Constant.ENCODING_UTF_8)); } catch (Exception e) { } finally { close(null, fos); } } private static void close(InputStream is, OutputStream os) { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } public static void unzip(String zipFilePath) throws IOException { String targetPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); unzip(zipFilePath, targetPath); } public static void unzip(String zipFilePath, String targetPath) throws IOException { ZipFile zipFile = new ZipFile(zipFilePath); try{ Enumeration entryEnum = zipFile.entries(); if (null != entryEnum) { while (entryEnum.hasMoreElements()) { OutputStream os = null; InputStream is = null; try { ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement(); if (!zipEntry.isDirectory()) { File targetFile = new File(targetPath + File.separator + zipEntry.getName()); if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } os = new BufferedOutputStream(new FileOutputStream(targetFile)); is = zipFile.getInputStream(zipEntry); byte[] buffer = new byte[4096]; int readLen = 0; while ((readLen = is.read(buffer, 0, 4096)) > 0) { os.write(buffer, 0, readLen); } } } finally { if (is != null) is.close(); if (os != null) os.close(); } } } }finally{ zipFile.close(); } } /** * 获取临时目录 */ public static String getTempPath(){ return System.getProperty("java.io.tmpdir"); } /** * 文件下载 * @param path * @param fileName * @param response */ public static void download(String path, String fileName, HttpServletResponse response){ File file=new File(path); if(!file.exists()){ throw new LanbaseException("文件不存在"); }else{ response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; OutputStream os = null; try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while(i != -1){ os.write(buffer); i = bis.read(buffer); } } catch (Exception e) { throw new LanbaseException("系统异常"); } finally { try { os.close(); bis.close(); fis.close(); } catch (Exception e) { throw new LanbaseException("系统异常"); } } } } //文件临时文件处理 public static void main(String[] args) { String fileName = "D:\\uploadFiles\\resource\\FileSource\\wenjianjia\\201805\\1665"; final long start = System.nanoTime(); final long total =getTotalSizeOfFilesInDir(new File(fileName)); final long end = System.nanoTime(); System.out.println("Total Size: " + total); System.out.println("Time taken: " + (end - start) / 1.0e9); } public static void copy(File file, File toFile) throws Exception { byte[] b = new byte[1024]; int a; FileInputStream fis; FileOutputStream fos; if (file.isDirectory()) { String filepath = file.getAbsolutePath(); filepath=filepath.replaceAll("\\\\", "/"); String toFilepath = toFile.getAbsolutePath(); toFilepath=toFilepath.replaceAll("\\\\", "/"); int lastIndexOf = filepath.lastIndexOf("/"); toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length()); File copy=new File(toFilepath); //复制文件夹 if (!copy.exists()) { copy.mkdir(); } //遍历文件夹 for (File f : file.listFiles()) { copy(f, copy); } } else { if (toFile.isDirectory()) { String filepath = file.getAbsolutePath(); filepath=filepath.replaceAll("\\\\", "/"); String toFilepath = toFile.getAbsolutePath(); toFilepath=toFilepath.replaceAll("\\\\", "/"); int lastIndexOf = filepath.lastIndexOf("/"); toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length()); //写文件 File newFile = new File(toFilepath); fis = new FileInputStream(file); fos = new FileOutputStream(newFile); while ((a = fis.read(b)) != -1) { fos.write(b, 0, a); } } else { //写文件 fis = new FileInputStream(file); fos = new FileOutputStream(toFile); while ((a = fis.read(b)) != -1) { fos.write(b, 0, a); } } } } public static void moveTotherFolders(String startPath,String endPath){ try { File startFile = new File(startPath); File tmpFile = new File(endPath);//获取文件夹路径 if(!tmpFile.exists()){//判断文件夹是否创建,没有创建则创建新文件夹 tmpFile.mkdirs(); } System.out.println(endPath +"\\"+startFile.getName()); if (startFile.renameTo(new File(endPath +"\\"+startFile.getName()))) { System.out.println("File is moved successful!"); } else { System.out.println("File is failed to move!"); } } catch (Exception e) { } } public static long getTotalSizeOfFilesInDir(final File file) { if (file.isFile()) return file.length(); final File[] children = file.listFiles(); long total = 0; if (children != null) for (final File child : children) total += getTotalSizeOfFilesInDir(child); return total; } public static String setSize(long size) { //获取到的size为:1705230 int GB = 1024 * 1024 * 1024;//定义GB的计算常量 int MB = 1024 * 1024;//定义MB的计算常量 int KB = 1024;//定义KB的计算常量 DecimalFormat df = new DecimalFormat("0.00");//格式化小数 String resultSize = ""; if (size / GB >= 1) { //如果当前Byte的值大于等于1GB resultSize = df.format(size / (float) GB) + " GB"; } else if (size / MB >= 1) { //如果当前Byte的值大于等于1MB resultSize = df.format(size / (float) MB) + " MB"; } else if (size / KB >= 1) { //如果当前Byte的值大于等于1KB resultSize = df.format(size / (float) KB) + " KB"; } else { resultSize = size + " B"; } return resultSize; } }