package com.newpay.common; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import com.rpcservice.common.CheckUtil; import com.rpcservice.common.Log; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; public class FileUtil { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); public static void main(String[] args) { String oldPath = "F:\git\project\newpay_java\newPay\src\Main.java"; String newPath = "F:\Main.java"; fileCopy(oldPath, newPath); } /** * 从网络Url中下载文件 * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+File.separator+fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); } /** * 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static boolean fileCopy(String oldPath, String newPath) { InputStream in = null; FileOutputStream os = null; try { in = new FileInputStream(oldPath); os = new FileOutputStream(newPath); int len; byte[] buf = new byte[1024]; while((len=in.read(buf))!= -1) {//包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null os.write(buf, 0, len); } } catch (Exception e) { } finally { if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); return false; } } if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; } /** * 写入文件 * * @param str 写入内容 * @param type 写入的文件在[log,image]文件夹下 * @param path 写入文件的文件名,带后缀 * @return */ public static boolean writeFile(String str, String type, String path) { PrintStream ps = null; try { File file = new File(CheckUtil.getSafePath(type, path)); ps = new PrintStream(new FileOutputStream(file)); if (null != ps) { ps.print(str); } return true; } catch (FileNotFoundException e) { return false; } finally { if (null != ps) { ps.close(); } } } /** * @param fileName * @param position * @param contents * @return * @throws Exception */ public static boolean insertFile(String fileName, int position, String contents, String type) throws Exception { if(null == contents || 0 >= contents.length()){ return false; } contents = new String(contents.getBytes("UTF-8"),"utf-8"); StringBuilder sb = new StringBuilder(type); sb.append("\").append(dateFormat.format(new Date())).append("\").append(fileName); //1、参数校验 File file = new File(sb.toString()); System.out.println(file); //判断文件是否存在 if (!(file.exists() && file.isFile())) { System.out.println("文件不存在 ~ "); file.createNewFile(); } //判断position是否合法 if ((position < 0) || (position > file.length())) { System.out.println("position不合法 ~ "); return false; } //2、创建临时文件 File tempFile = File.createTempFile("sss", ".temp", new File("d:/")); //File tempFile = new File("d:/wwwww.txt"); //3、用文件输入流、文件输出流对文件进行操作 FileOutputStream outputStream = new FileOutputStream(tempFile); FileInputStream inputStream = new FileInputStream(tempFile); //在退出JVM退出时自动删除 tempFile.deleteOnExit(); //4、创建RandomAccessFile流 RandomAccessFile rw = new RandomAccessFile(file, "rw"); //文件指定位置到 position rw.seek(position); int tmp; //5、将position位置后的内容写入临时文件 while ((tmp = rw.read()) != -1) { outputStream.write(tmp); } //6、将追加内容 contents 写入 position 位置 rw.seek(position); rw.write(contents.getBytes()); //7、将临时文件写回文件,并将创建的流关闭 while ((tmp = inputStream.read()) != -1) { rw.write(tmp); } rw.close(); outputStream.close(); inputStream.close(); return true; } /** * 追加写入文件 * * @param str 写入内容 * @return */ public static boolean writeAddFile(String str, String fileName, String type) { try { str = new String(str.getBytes("UTF-8"),"utf-8"); } catch (UnsupportedEncodingException e) { return false; } StringBuilder sb = new StringBuilder(type).append("\").append(dateFormat.format(new Date())); FileWriter ps = null; try { File file = new File(sb.toString()); if (!file.exists()) { file.mkdirs(); } sb.append("\").append(fileName); file = new File(sb.toString()); if (!file.exists()) { file.createNewFile(); } ps = new FileWriter(sb.toString(), true); //ps = new PrintStream(new FileOutputStream(file)); if (null != ps) { ps.write(str); } return true; } catch (FileNotFoundException e) { return false; } catch (IOException e) { e.printStackTrace(); } finally { if (null != ps) { try { ps.close(); } catch (IOException e) { e.printStackTrace(); return false; } } } return false; } /** * 将图片文件获取成String * * @param type 读取的图片在[log,image]文件夹下 * @param path 读取的图片的文件名,带后缀 * @return */ public static String getImgfromFile(String type, String path) { InputStream in = null; byte[] data = null; try { in = new FileInputStream(CheckUtil.getSafePath(type, path)); if (null != in) { data = new byte[in.available()]; in.read(data); } in.close(); } catch (Exception e) { Log.error(e.toString()); } return Base64.encode(data); } /** * 读文件 * * @param type 读取的文件在[log,image]文件夹下 * @param path 读取的文件的文件名,带后缀 */ public static String getFile(String type, String path) { String result = null; File file = new File(CheckUtil.getSafePath(type, path)); Long fileLength = file.length(); byte[] fileContent = new byte[fileLength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(fileContent); in.close(); result = new String(fileContent, "UTF-8"); } catch (Exception e) { System.out.println(e + " [读取文本文件内容错误]"); } return result; } public static File doZip(String sourceDir, String zipFilePath) throws IOException { File file = new File(sourceDir); File zipFile = new File(zipFilePath); if(!zipFile.exists()){ zipFile.mkdirs(); } ZipOutputStream zos = null; try { String basePath = null; //获取目录 if (file.isDirectory()) { basePath = file.getPath(); } else { basePath = file.getParent(); } zipFile(file, basePath, zos); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (zos != null) { zos.closeEntry(); zos.close(); } } return zipFile; } private static void zipFile(File file, String basePath, ZipOutputStream zos) throws IOException { File[] files = null; if (file.isDirectory()) { files = file.listFiles(); }else{ files = new File[1]; files[0] = file; } InputStream is = null; String pathName; byte[] buf = new byte[1024]; int length = 0; try{ for (File f:files){ if(f.isDirectory()){ pathName = f.getPath().substring(basePath.length()+1)+"/"; zos.putNextEntry(new ZipEntry(pathName)); zipFile(f,basePath,zos); }else{ pathName = f.getPath().substring(basePath.length()+1)+"/"; File zipFile = new File(pathName); OutputStream os = new FileOutputStream(zipFile); BufferedOutputStream bos = new BufferedOutputStream(os); zos = new ZipOutputStream(bos); is = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(is); ZipEntry zipEntry = new ZipArchiveEntry(pathName); zos.putNextEntry(zipEntry); while ((length = bis.read(buf))>0){ zos.write(buf,0,length); } } } } catch (IOException e) { e.printStackTrace(); } finally { if(is != null){ is.close(); } } } /** * 读取文件 返回二进制内容 * @param filePath * @return */ public static byte[] readFile(String filePath){ byte[] fileContent = null; FileInputStream is = null; try { is = new FileInputStream(filePath); fileContent = new byte[is.available()]; int len = 0; while((len = is.read(fileContent)) != -1) { ; } } catch (IOException e) { Log.error(e.getMessage()); } finally { if (null != is) { try { is.close(); } catch (IOException e) { Log.error(e.getMessage()); } } } return fileContent; } /** * 删除单个文件 * * @param fileName * 要删除的文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFile(String fileName) { File file = new File(fileName); // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 if (file.exists() && file.isFile()) { if (file.delete()) { System.out.println("删除单个文件" + fileName + "成功!"); return true; } else { System.out.println("删除单个文件" + fileName + "失败!"); return false; } } else { System.out.println("删除单个文件失败:" + fileName + "不存在!"); return false; } } /** * 删除目录及目录下的文件 * @param dir * 要删除的目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String dir) { // 如果dir不以文件分隔符结尾,自动添加文件分隔符 if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); // 如果dir对应的文件不存在,或者不是一个目录,则退出 if ((!dirFile.exists()) || (!dirFile.isDirectory())) { System.out.println("删除目录失败:" + dir + "不存在!"); return false; } boolean flag = true; // 删除文件夹中的所有文件包括子目录 File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // 删除子文件 if (files[i].isFile()) { flag = FileUtil.deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } // 删除子目录 else if (files[i].isDirectory()) { flag = FileUtil.deleteDirectory(files[i] .getAbsolutePath()); if (!flag) { break; } } } if (!flag) { System.out.println("删除目录失败!"); return false; } // 删除当前目录 if (dirFile.delete()) { System.out.println("删除目录" + dir + "成功!"); return true; } else { return false; } } }