Java操作文件的常用方法

深碍√TFBOYSˉ_ 2022-03-25 03:14 392阅读 0赞

1.包含: 解压文件、读取文件内容、删除文件、删除文件夹、将图片转换成二进制与还原。

2.FileUtils.java:

  1. import java.awt.image.BufferedImage;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.util.Enumeration;
  12. import javax.imageio.ImageIO;
  13. import org.apache.tools.zip.ZipEntry;
  14. import org.apache.tools.zip.ZipFile;
  15. import org.junit.Test;
  16. import sun.misc.BASE64Decoder;
  17. import sun.misc.BASE64Encoder;
  18. public class FileUtils {
  19. private static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
  20. private static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
  21. public FileUtils() {
  22. }
  23. /**
  24. * @param sourcefiles
  25. * 源文件(服务器上的zip包存放地址)
  26. * @param decompreDirectory
  27. * 解压缩后文件存放的目录
  28. * @throws IOException
  29. * IO异常
  30. */
  31. public static void unzip(String sourcefiles, String decompreDirectory) throws IOException {
  32. ZipFile readfile = null;
  33. try {
  34. readfile = new ZipFile(sourcefiles);
  35. Enumeration<?> takeentrie = readfile.getEntries();
  36. ZipEntry zipEntry = null;
  37. File credirectory = new File(decompreDirectory);
  38. credirectory.mkdirs();
  39. while (takeentrie.hasMoreElements()) {
  40. zipEntry = (ZipEntry) takeentrie.nextElement();
  41. String entryName = zipEntry.getName();
  42. InputStream in = null;
  43. FileOutputStream out = null;
  44. try {
  45. if (zipEntry.isDirectory()) {
  46. String name = zipEntry.getName();
  47. name = name.substring(0, name.length() - 1);
  48. File createDirectory = new File(decompreDirectory + File.separator + name);
  49. createDirectory.mkdirs();
  50. } else {
  51. int index = entryName.lastIndexOf("\\");
  52. if (index != -1) {
  53. File createDirectory = new File(
  54. decompreDirectory + File.separator + entryName.substring(0, index));
  55. createDirectory.mkdirs();
  56. }
  57. index = entryName.lastIndexOf("/");
  58. if (index != -1) {
  59. File createDirectory = new File(
  60. decompreDirectory + File.separator + entryName.substring(0, index));
  61. createDirectory.mkdirs();
  62. }
  63. File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName());
  64. in = readfile.getInputStream(zipEntry);
  65. out = new FileOutputStream(unpackfile);
  66. int c;
  67. byte[] by = new byte[1024];
  68. while ((c = in.read(by)) != -1) {
  69. out.write(by, 0, c);
  70. }
  71. out.flush();
  72. }
  73. } catch (IOException ex) {
  74. ex.printStackTrace();
  75. throw new IOException("解压失败:" + ex.toString());
  76. } finally {
  77. if (in != null) {
  78. try {
  79. in.close();
  80. } catch (IOException ex) {
  81. }
  82. }
  83. if (out != null) {
  84. try {
  85. out.close();
  86. } catch (IOException ex) {
  87. ex.printStackTrace();
  88. }
  89. }
  90. in = null;
  91. out = null;
  92. }
  93. }
  94. } catch (IOException ex) {
  95. ex.printStackTrace();
  96. throw new IOException("解压失败:" + ex.toString());
  97. } finally {
  98. if (readfile != null) {
  99. try {
  100. readfile.close();
  101. } catch (IOException ex) {
  102. ex.printStackTrace();
  103. throw new IOException("解压失败:" + ex.toString());
  104. }
  105. }
  106. }
  107. }
  108. /**
  109. * @param filePath
  110. * @param encode
  111. * @return 读取文件内容
  112. * @throws Exception
  113. */
  114. public static String readFile(String filePath) {
  115. return readFile(filePath, "utf-8");
  116. }
  117. /**
  118. * @param filePath
  119. * @param encode
  120. * @param limit
  121. * @return 读取文件内容
  122. * @throws Exception
  123. */
  124. public static String readFile(String filePath, String encode) {
  125. String result = "";
  126. File file = new File(filePath);
  127. FileInputStream inputStream = null;
  128. InputStreamReader inputReader = null;
  129. try {
  130. inputStream = new FileInputStream(file);
  131. inputReader = new InputStreamReader(inputStream, encode);
  132. BufferedReader br = new BufferedReader(inputReader);
  133. String str = "";
  134. while ((str = br.readLine()) != null) {
  135. result += str + "\n"; // TODO \n
  136. }
  137. } catch (Exception ex) {
  138. ex.printStackTrace();
  139. } finally {
  140. try {
  141. inputReader.close();
  142. inputStream.close();
  143. } catch (IOException e) {
  144. e.printStackTrace();
  145. }
  146. }
  147. return result;
  148. }
  149. /**
  150. * @param filePath
  151. * @return 删除文件
  152. */
  153. public static boolean delFile(String filePath) {
  154. boolean flag = false;
  155. File file = new File(filePath);
  156. if (file.isFile() && file.exists()) {
  157. flag = file.delete();
  158. }
  159. return flag;
  160. }
  161. /**
  162. * @param dir
  163. * @return 删除文件夹
  164. */
  165. public static boolean deleteDir(File dir) {
  166. if (dir.isDirectory()) {
  167. String[] children = dir.list();
  168. // 递归删除目录中的子目录下
  169. for (int i = 0; i < children.length; i++) {
  170. boolean success = deleteDir(new File(dir, children[i]));
  171. if (!success) {
  172. return false;
  173. }
  174. }
  175. }
  176. // 目录此时为空,可以删除
  177. return dir.delete();
  178. }
  179. /**
  180. * 将图片转换成二进制
  181. * @return
  182. */
  183. public static String getImageBinary(File file) {
  184. String fileName = file.getName();
  185. // System.out.println(fileName + " " + fileName.substring(fileName.indexOf(".")+1, fileName.length()));
  186. BufferedImage bi;
  187. try {
  188. bi = ImageIO.read(file);
  189. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  190. ImageIO.write(bi, fileName.substring(fileName.indexOf(".")+1, fileName.length()), baos); // 经测试转换的图片是格式这里就什么格式,否则会失真
  191. byte[] bytes = baos.toByteArray();
  192. return encoder.encodeBuffer(bytes).trim();
  193. } catch (IOException e) {
  194. e.printStackTrace();
  195. }
  196. return null;
  197. }
  198. /**
  199. * @param base64String
  200. * @param savePath
  201. * @param type
  202. * 将二进制转换为图片
  203. */
  204. public static void base64StringToImage(String base64String, String savePath) {
  205. try {
  206. byte[] bytes1 = decoder.decodeBuffer(base64String);
  207. ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
  208. BufferedImage bi1 = ImageIO.read(bais);
  209. File w2 = new File(savePath);// File w2 = new File("e://QQ.jpg") 可以是jpg,png,gif格式
  210. // TODO jpg
  211. ImageIO.write(bi1, savePath.substring(savePath.indexOf(".")+1, savePath.length()), w2);// 不管输出什么格式图片,此处不需改动
  212. } catch (IOException e) {
  213. e.printStackTrace();
  214. }
  215. }
  216. // 解压 zip
  217. public static void main(String[] args) {
  218. try {
  219. unzip("D:/workplace/Producer/files/20190116.zip",
  220. "D:/workplace/Producer/files/abc");
  221. } catch (IOException e) {
  222. e.printStackTrace();
  223. }
  224. }
  225. // 读取内容
  226. @Test
  227. public void test01() {
  228. System.out.println(
  229. readFile("D:/workplace/Producer/files/20190116/1547449028337.txt"));
  230. }
  231. // 删除文件夹
  232. @Test
  233. public void test02() throws IOException {
  234. unzip("D:/workplace/Producer/files/20190116.zip",
  235. "D:/workplace/Producer/files/");
  236. deleteDir(new File("D:/workplace/Producer/files/20190116"));
  237. }
  238. // 文件属性
  239. @Test
  240. public void test03() throws IOException {
  241. File file = new File("D:/workplace/Producer/files/20190116.zip");
  242. System.out.println(file.getAbsolutePath());
  243. System.out.println(file.getCanonicalPath());
  244. System.out.println(file.getPath());
  245. System.out.println(file.getTotalSpace());
  246. System.out.println(file.getFreeSpace());
  247. System.out.println(file.getUsableSpace());
  248. System.out.println(file.getParent());
  249. }
  250. // 图片处理
  251. @Test
  252. public void test04() {
  253. String photo = getImageBinary(new File("D:/workplace/Producer/files/714b348d35e1e1ec3d5c769c8bbdb727__1.jpg"));
  254. System.out.println(photo);
  255. base64StringToImage(photo, "D:/workplace/Producer/files/20190114/a.jpg");
  256. }
  257. @Test
  258. public void test05() {
  259. String str = "abc\ndef\nghi";
  260. String str_[] = str.split("\n");
  261. System.out.println( str_.length + " " + str_[0] + "," + str_[1] + "," + str_[2] );
  262. }
  263. }

发表评论

表情:
评论列表 (有 0 条评论,392人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ant 文件操作

    4.5 Copy Task:对文件和目录进行复制 Copy 任务把一个或多个文件复制到指定的目录下。但要注意的是,如果目标目录下具有同名的文件,那么只有当源文件相对于目标