package org.newboy.io; import java.io.*; /** * 用于对文件和文件夹的一般操作,包括新建、删除、移动、复制等 */ public class FileUtils { /** * 新建目录,并且可以建立多层 * @param folderPath String 如 c:/temp * @return 目录建成功返回真 */ public static boolean newFolder(String folderPath) { try { File myFilePath = new File(folderPath); if (!myFilePath.exists()) { myFilePath.mkdirs(); } } catch (Exception e) { System.out.println("目录已经存在或新建目录操作时出现错误"); e.printStackTrace(); return false; } return true; } /** * 新建文件 * @param filePathAndName String 文件路径及名称 如c:/newboy.txt * @param fileContent String 文件内容 * @return 新建成功返回真 */ public static boolean newFile(String filePathAndName, String fileContent) { try { String filePath = filePathAndName; filePath = filePath.toString(); File myFilePath = new File(filePath); if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); String strContent = fileContent; myFile.println(strContent); resultFile.close(); } catch (Exception e) { System.out.println("新建文件时出现错误"); e.printStackTrace(); return false; } return true; } /** * 删除文件 * @param filePathAndName String 文件路径及名称 如c:/newboy.txt * @param fileContent String * @return boolean 删除成功返回真 */ public static boolean deleteFile(String filePathAndName) { boolean flag = false; try { String filePath = filePathAndName; filePath = filePath.toString(); File myDelFile = new File(filePath); flag = myDelFile.delete(); } catch (Exception e) { System.out.println("删除文件:" + filePathAndName + "时出现错误"); e.printStackTrace(); flag = false; } return flag; } /** * 删除文件夹 * @param filePathAndName String 文件夹路径及名称 如c:/newboy * @param fileContent String * @return 删除成功返回真 */ public static boolean deleteFolder(String folderPath) { try { deleteAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); File myFilePath = new File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { System.out.println("删除文件夹操作出错"); e.printStackTrace(); return false; } return true; } /** * 删除文件夹里面的所有文件 * @param path String 文件夹路径 如 c:/newboy * @return 删除成功返回真 */ public static boolean deleteAllFile(String path) { File file = new File(path); if (!file.exists()) { return false; } if (!file.isDirectory()) { return false; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { deleteAllFile(path + "/" + tempList[i]); //先删除文件夹里面的文件 deleteFolder(path + "/" + tempList[i]); //再删除空文件夹 } } return true; } /** * 复制单个文件 * @param oldPath String 原文件路径 如:c:/newboy.txt * @param newPath String 复制后路径 如:f:/newboy.txt * @return 复制成功返回真 */ public static boolean copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldPath); //读入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制文件" + oldPath + "时出现错误"); e.printStackTrace(); return false; } return true; } /** * 复制整个文件夹内容 * @param oldPath String 原文件路径 如:c:/newboy * @param newPath String 复制后路径 如:f:/newboy/ff * @return 成功返回真 */ public static boolean copyFolder(String oldPath, String newPath) { try { newFolder(newPath); //如果文件夹不存在则建立新文件夹 File a = new File(oldPath); String[] file = a.list(); File temp = null; for (int i = 0; i < file.length; i++) { if (oldPath.endsWith(File.separator)) { temp = new File(oldPath + file[i]); } else { temp = new File(oldPath + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] b = new byte[1024 * 5]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) { //如果是子文件夹 copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹时,出现错误"); e.printStackTrace(); return false; } return true; } /** * 移动文件到指定目录 * @param sourcePath 源目录 String 如:c:/newboy.txt * @param targetPath 目标目录 String 如:d:/newboy.txt */ public static void moveFile(String sourcePath, String targetPath) { copyFile(sourcePath, targetPath); deleteFile(sourcePath); } /** * 移动文件到指定目录 * @param sourcePath String 如:c:/newboy.txt * @param targetPath String 如:d:/newboy.txt */ public static void moveFolder(String sourcePath, String targetPath) { copyFolder(sourcePath, targetPath); deleteFolder(sourcePath); } /** * 打开文本文件 * @param fileName 文件名 * @return 打开的文件内容 */ public static String openFile(String fileName) { StringBuffer sb = null; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); String temp = br.readLine(); sb = new StringBuffer(); //最后总会多一个换行 while (temp != null) { sb.append(temp); sb.append("/r/n"); temp = br.readLine(); } br.close(); } catch (FileNotFoundException ex) { System.err.println("找不到指定的文件"); } catch (IOException ex) { System.err.println("文件读写出现异常"); } return sb.toString(); } /** * 将content的内容写到一个文本文件中 * @param fileName 文件名 * @param content 内容 * @return 写入成功返回真 */ public static boolean saveToFile(String fileName, String content) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < content.length(); i++) { // /r和/n才是换行 if (content.charAt(i) == '/r' && content.charAt(i) == '/n') { bw.newLine(); i++; //要跳两个过去 } else { bw.write(content.charAt(i)); } //把它做为一个字符整型写入,自动转型 } bw.close(); } catch (IOException ex) { ex.printStackTrace(); return false; } return true; } /**----------------------------------------------------------------------- *getAppPath需要一个当前程序使用的Java类的class属性参数,它可以返回打包过的 *Java可执行文件(jar,war)所处的系统目录名或非打包Java程序所处的目录 *@param cls为Class类型 *@return 返回值为该类所在的Java程序运行的目录 -------------------------------------------------------------------------*/ public static String getAppPath(Class cls) { //检查用户传入的参数是否为空 if (cls == null) { throw new java.lang.IllegalArgumentException("参数不能为空!"); } ClassLoader loader = cls.getClassLoader(); //获得类的全名,包括包名 String clsName = cls.getName() + ".class"; //获得传入参数所在的包 Package pack = cls.getPackage(); String path = ""; //如果不是匿名包,将包名转化为路径 if (pack != null) { String packName = pack.getName(); //此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库 if (packName.startsWith("java.") || packName.startsWith("javax.")) { throw new java.lang.IllegalArgumentException("不要传送系统类!"); } //在类的名称中,去掉包名的部分,获得类的文件名 clsName = clsName.substring(packName.length() + 1); //判定包名是否是简单包名,如果是,则直接将包名转换为路径, if (packName.indexOf(".") < 0) { path = packName + "/"; } else { //否则按照包名的组成部分,将包名转换为路径 int start = 0, end = 0; end = packName.indexOf("."); while (end != -1) { path = path + packName.substring(start, end) + "/"; start = end + 1; end = packName.indexOf(".", start); } path = path + packName.substring(start) + "/"; } } //调用ClassLoader的getResource方法,传入包含路径信息的类文件名 java.net.URL url = loader.getResource(path + clsName); //从URL对象中获取路径信息 String realPath = url.getPath(); //去掉路径信息中的协议名"file:" int pos = realPath.indexOf("file:"); if (pos > -1) { realPath = realPath.substring(pos + 5); } //去掉路径信息最后包含类文件信息的部分,得到类所在的路径 pos = realPath.indexOf(path + clsName); realPath = realPath.substring(0, pos - 1); //如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名 if (realPath.endsWith("!")) { realPath = realPath.substring(0, realPath.lastIndexOf("/")); } /*------------------------------------------------------------ ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要 的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的 中文及空格路径 -------------------------------------------------------------*/ try { realPath = java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } return realPath; } //getAppPath定义结束 }