FileUtils.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package com.jsh.erp.utils;
  2. import javax.servlet.http.HttpServletRequest;
  3. import java.io.*;
  4. import java.net.URLEncoder;
  5. import java.util.*;
  6. /**
  7. *
  8. * 文件处理工具类
  9. *
  10. */
  11. public class FileUtils {
  12. /**
  13. * 功 能: 创建文件夹
  14. *
  15. * @param path
  16. * 参 数:要创建的文件夹名称
  17. * @return 返回值: 如果成功true;否则false 如:FileUtils.mkdir("/usr/apps/upload/");
  18. */
  19. public static boolean makedir(String path) {
  20. File file = new File(path);
  21. if (!file.exists())
  22. return file.mkdirs();
  23. else
  24. return true;
  25. }
  26. /**
  27. * 保存文件
  28. *
  29. * @param stream
  30. * @param path
  31. * 存放路径
  32. * @param filename
  33. * 文件名
  34. * @throws IOException
  35. */
  36. public static void SaveFileFromInputStream(InputStream stream, String path, String filename)
  37. throws IOException {
  38. File file = new File(path);
  39. boolean flag=true;
  40. if(!file.exists()){
  41. flag=file.mkdirs();
  42. }
  43. if(flag){
  44. FileOutputStream fs = new FileOutputStream(new File(path+filename));
  45. byte[] buffer = new byte[1024 * 1024];
  46. int byteread = 0;
  47. while ((byteread = stream.read(buffer)) != -1) {
  48. fs.write(buffer, 0, byteread);
  49. fs.flush();
  50. }
  51. fs.close();
  52. stream.close();
  53. }
  54. }
  55. /**
  56. * 列出某个目录下的所有文件,子目录不列出
  57. * @param folderPath:文件夹路径
  58. * @return
  59. */
  60. public static List<String> listFile(String folderPath){
  61. List<String> fileList = new ArrayList<String>(); //FileViewer.getListFiles(destPath, null, false);
  62. File f = new File(folderPath);
  63. File[] t = f.listFiles();
  64. for(int i = 0; i < t.length; i++){
  65. fileList.add(t[i].getAbsolutePath());
  66. }
  67. return fileList;
  68. }
  69. /**
  70. * 判断文件是否存在
  71. *
  72. * @param fileName
  73. * @return
  74. */
  75. public static boolean exists(String fileName) {
  76. File file = new File(fileName);
  77. if (file.exists()) {
  78. return true;
  79. } else {
  80. return false;
  81. }
  82. }
  83. /**
  84. * 获取文件扩展名
  85. *
  86. * @param fileName
  87. * @return
  88. * */
  89. public static String getFileExtendName(String fileName) {
  90. if (fileName == null) {
  91. return "";
  92. } else {
  93. return fileName.substring(fileName.lastIndexOf(".") + 1, fileName
  94. .length());
  95. }
  96. }
  97. /**
  98. * 创建一个新文件,如果存在则报错
  99. *
  100. * @param filePath
  101. * @param fileName
  102. * @return
  103. */
  104. public static void createFile(String filePath, String fileName)
  105. throws RuntimeException {
  106. String file = null;
  107. if (filePath == null) {
  108. file = fileName;
  109. } else {
  110. file = filePath + File.separator + fileName;
  111. }
  112. createFile(file);
  113. }
  114. /**
  115. * 创建一个新文件(含路径),如果存在则报错
  116. *
  117. * @param fileName
  118. * 含有路径的文件名
  119. * @return
  120. */
  121. public static void createFile(String fileName) throws RuntimeException {
  122. File f = new File(fileName);
  123. if (f.exists()) {
  124. throw new RuntimeException("FILE_EXIST_ERROR");
  125. } else {
  126. try {
  127. File fileFolder = f.getParentFile();
  128. if (!fileFolder.exists())
  129. fileFolder.mkdirs();
  130. f.createNewFile();
  131. } catch (IOException ie) {
  132. System.out.println("文件" + fileName + "创建失败:" + ie.getMessage());
  133. throw new RuntimeException("FILE_CREATE_ERROR");
  134. }
  135. }
  136. }
  137. /**
  138. * 创建目录,如果存在则不创建
  139. *
  140. * @param path
  141. * @return 返回结果null则创建成功,否则返回的是错误信息
  142. * @return
  143. */
  144. public static String createDir(String path, boolean isCreateSubPah) {
  145. String msg = null;
  146. File dir = new File(path);
  147. if (dir == null) {
  148. msg = "不能创建空目录";
  149. return msg;
  150. }
  151. if (dir.isFile()) {
  152. msg = "已有同名文件存在";
  153. return msg;
  154. }
  155. if (!dir.exists()) {
  156. if (isCreateSubPah && !dir.mkdirs()) {
  157. msg = "目录创建失败,原因不明";
  158. } else if (!dir.mkdir()) {
  159. msg = "目录创建失败,原因不明";
  160. }
  161. }
  162. return msg;
  163. }
  164. /**
  165. * 删除指定目录或文件。 如果要删除是目录,同时删除子目录下所有的文件
  166. *
  167. * @file:File 目录
  168. * */
  169. public static void delFileOrFolder(String fileName) {
  170. if (!exists(fileName))
  171. return;
  172. File file = new File(fileName);
  173. delFileOrFolder(file);
  174. }
  175. /**
  176. * 删除指定目录或文件。 如果要删除是目录,同时删除子目录下所有的文件
  177. *
  178. * @file:File 目录
  179. * */
  180. public static void delFileOrFolder(File file) {
  181. if (!file.exists())
  182. return;
  183. if (file.isFile()) {
  184. file.delete();
  185. } else {
  186. File[] sub = file.listFiles();
  187. if (sub == null || sub.length <= 0) {
  188. file.delete();
  189. } else {
  190. for (int i = 0; i < sub.length; i++) {
  191. delFileOrFolder(sub[i]);
  192. }
  193. file.delete();
  194. }
  195. }
  196. }
  197. /**
  198. * 从Properties格式配置文件中获取所有参数并保存到HashMap中。
  199. * 配置中的key值即map表中的key值,如果配置文件保存时用的中文,则返回结果也会转成中文。
  200. *
  201. * @param file
  202. * @return
  203. * @throws IOException
  204. */
  205. @SuppressWarnings("unchecked")
  206. public static HashMap readPropertyFile(String file, String charsetName) throws IOException {
  207. if (charsetName==null || charsetName.trim().length()==0){
  208. charsetName="gbk";
  209. }
  210. HashMap map = new HashMap();
  211. InputStream is =null;
  212. if(file.startsWith("file:"))
  213. is=new FileInputStream(new File(file.substring(5)));
  214. else
  215. is=FileUtils.class.getClassLoader().getResourceAsStream(file);
  216. Properties properties = new Properties();
  217. properties.load(is);
  218. Enumeration en = properties.propertyNames();
  219. while (en.hasMoreElements()) {
  220. String key = (String) en.nextElement();
  221. String code = new String(properties.getProperty(key).getBytes(
  222. "ISO-8859-1"), charsetName);
  223. map.put(key, code);
  224. }
  225. return map;
  226. }
  227. /**
  228. *
  229. * @param path
  230. * 文件路径
  231. * @param suffix
  232. * 后缀名
  233. * @param isdepth
  234. * 是否遍历子目录
  235. * @return
  236. */
  237. @SuppressWarnings("unchecked")
  238. public static List getListFiles(String path, String suffix, boolean isdepth) {
  239. File file = new File(path);
  240. return FileUtils.listFile(file, suffix, isdepth);
  241. }
  242. /**
  243. * @param f
  244. * @param suffix:后缀名
  245. * @param isdepth:是否遍历子目录
  246. * @return
  247. */
  248. @SuppressWarnings("unchecked")
  249. public static List listFile(File f, String suffix, boolean isdepth) {
  250. // 是目录,同时需要遍历子目录
  251. List<String> fileList = new ArrayList<String>();
  252. if (f.isDirectory() && isdepth == true) {
  253. File[] t = f.listFiles();
  254. for (int i = 0; i < t.length; i++) {
  255. listFile(t[i], suffix, isdepth);
  256. }
  257. } else {
  258. String filePath = f.getAbsolutePath();
  259. if (suffix != null) {
  260. int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
  261. String tempsuffix = "";
  262. if (begIndex != -1)// 防止是文件但却没有后缀名结束的文件
  263. {
  264. tempsuffix = filePath.substring(begIndex + 1, filePath
  265. .length());
  266. }
  267. if (tempsuffix.equals(suffix)) {
  268. fileList.add(filePath);
  269. }
  270. } else {
  271. // 后缀名为null则为所有文件
  272. fileList.add(filePath);
  273. }
  274. }
  275. return fileList;
  276. }
  277. /**
  278. * 判断文件名是否带盘符,重新处理
  279. * @param fileName
  280. * @return
  281. */
  282. public static String getFileName(String fileName){
  283. //判断是否带有盘符信息
  284. // Check for Unix-style path
  285. int unixSep = fileName.lastIndexOf('/');
  286. // Check for Windows-style path
  287. int winSep = fileName.lastIndexOf('\\');
  288. // Cut off at latest possible point
  289. int pos = (winSep > unixSep ? winSep : unixSep);
  290. if (pos != -1) {
  291. // Any sort of path separator found...
  292. fileName = fileName.substring(pos + 1);
  293. }
  294. //替换上传文件名字的特殊字符
  295. fileName = fileName.replace("=","").replace(",","").replace("&","");
  296. return fileName;
  297. }
  298. public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
  299. throws UnsupportedEncodingException
  300. {
  301. final String agent = request.getHeader("USER-AGENT");
  302. String filename = fileName;
  303. if (agent.contains("MSIE"))
  304. {
  305. // IE浏览器
  306. filename = URLEncoder.encode(filename, "utf-8");
  307. filename = filename.replace("+", " ");
  308. }
  309. else if (agent.contains("Firefox"))
  310. {
  311. // 火狐浏览器
  312. filename = new String(fileName.getBytes(), "ISO8859-1");
  313. }
  314. else if (agent.contains("Chrome"))
  315. {
  316. // google浏览器
  317. filename = URLEncoder.encode(filename, "utf-8");
  318. }
  319. else
  320. {
  321. // 其它浏览器
  322. filename = URLEncoder.encode(filename, "utf-8");
  323. }
  324. return filename;
  325. }
  326. }