java读取文件,写入文件

朱雀 2024-03-30 17:26 198阅读 0赞

Java 中 IO 流

Java 中 IO 流分为几种?

按照流的流向分,可以分为输入流和输出流;

按照操作单元划分,可以划分为字节流和字符流;

按照流的角色划分为节点流和处理流。

Java Io 流共涉及 40 多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧

密的联系, Java I0 流的 40 多个类都是从如下 4 个抽象类基类中派生出来的。

InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。

OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。

递归读取文件夹下的文件,代码怎么实现

  1. /**
  2. * 递归读取文件夹下的 所有文件
  3. *
  4. * @param testFileDir 文件名或目录名
  5. */
  6. private static void testLoopOutAllFileName(String testFileDir) {
  7. if (testFileDir == null) {
  8. //因为new File(null)会空指针异常,所以要判断下
  9. return;
  10. }
  11. File[] testFile = new File(testFileDir).listFiles();
  12. if (testFile == null) {
  13. return;
  14. }
  15. for (File file : testFile) {
  16. if (file.isFile()) {
  17. System.out.println(file.getName());
  18. } else if (file.isDirectory()) {
  19. System.out.println("-------file-------" + file.getName());
  20. testLoopOutAllFileName(file.getPath());
  21. } else {
  22. System.out.println("文件读入有误!");
  23. }
  24. }
  25. }

文件操作工具类:

  1. package com.fyg.common.util;
  2. import com.fyg.common.constants;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.tools.tar.TarEntry;
  5. import org.apache.tools.tar.TarInputStream;
  6. import java.io.*;
  7. import java.nio.charset.Charset;
  8. import java.text.DecimalFormat;
  9. import java.util.*;
  10. import java.util.zip.GZIPInputStream;
  11. import java.util.zip.ZipEntry;
  12. import java.util.zip.ZipFile;
  13. import java.util.zip.ZipInputStream;
  14. /**
  15. * 操作文件的辅助类
  16. *
  17. * @author liqh
  18. * @version 1.0
  19. */
  20. @Slf4j
  21. public class FileUtils extends org.apache.commons.io.FileUtils {
  22. public static final String B_UNIT = "B";
  23. public static final String KB_UNIT = "KB";
  24. public static final String MB_UNIT = "MB";
  25. public static final String GB_UNIT = "GB";
  26. public static final DecimalFormat decimalFormat = new DecimalFormat("#.0");
  27. /**
  28. * 创建目录
  29. *
  30. * @param dir
  31. * @return
  32. */
  33. public static boolean createDirectory(String dir) {
  34. if (!isExistsDirectory(dir)) {
  35. File folder = new File(dir);
  36. return folder.mkdirs();
  37. }
  38. return false;
  39. }
  40. /**
  41. * 判断当前目录是否存在
  42. *
  43. * @param dir
  44. * @return true:存在 false:不存在
  45. */
  46. public static boolean isExistsDirectory(String dir) {
  47. File folder = new File(dir);
  48. if (!folder.exists() && !folder.isDirectory()) {
  49. return false;
  50. }
  51. return true;
  52. }
  53. /**
  54. * 创建新的文件名
  55. */
  56. public static String renameToUUID(String fileName) {
  57. return IDUtils.generateId32() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
  58. }
  59. /**
  60. * 创建文件
  61. *
  62. * @param fileName
  63. * @return true:创建成功 false:创建失败
  64. * @throws IOException
  65. */
  66. public static boolean createNewFile(String fileName) throws IOException {
  67. if (!isExistsFile(fileName)) {
  68. File file = new File(fileName);
  69. return file.createNewFile();
  70. }
  71. return false;
  72. }
  73. /**
  74. * 判断当前文件是否存在
  75. *
  76. * @param fileName
  77. * @return true:存在 false:不存在
  78. */
  79. public static boolean isExistsFile(String fileName) {
  80. File file = new File(fileName);
  81. return file.exists();
  82. }
  83. /**
  84. * 获取某个文件夹下的所有文件,只包含文件
  85. *
  86. * @param dir
  87. * @return
  88. */
  89. public static List<String> getFileList(String dir) {
  90. List<String> fileNameList = new ArrayList<>();
  91. File file = new File(dir);
  92. File[] tempList = file.listFiles();
  93. for (int i = 0; i < tempList.length; i++) {
  94. if (tempList[i].isFile()) {
  95. fileNameList.add(tempList[i].getName());
  96. }
  97. }
  98. return fileNameList;
  99. }
  100. /**
  101. * 获取某个文件夹下的所有文件全路径
  102. *
  103. * @param dir
  104. * @return
  105. */
  106. public static List<String> getAllFileAbsolute(String dir) {
  107. List<String> fileNameList = new ArrayList<>();
  108. return getAllFileAbsolute(dir, fileNameList);
  109. }
  110. /**
  111. * 获取某个文件夹下的所有文件,包含文件夹和文件
  112. *
  113. * @param dir
  114. * @return
  115. */
  116. public static List<String> getAllFileAbsolute(String dir, List<String> fileNameList) {
  117. File file = new File(dir);
  118. File[] tempList = file.listFiles();
  119. for (int i = 0; i < tempList.length; i++) {
  120. if (tempList[i].isFile()) {
  121. fileNameList.add(tempList[i].toString());
  122. } else if (tempList[i].isDirectory()) {
  123. getAllFileAbsolute(tempList[i].getAbsolutePath(), fileNameList);
  124. }
  125. }
  126. return fileNameList;
  127. }
  128. /**
  129. * 获取某个文件夹下的所有文件,包含文件夹和文件
  130. *
  131. * @param dir
  132. * @return
  133. */
  134. public static List<String> getAllFileName(String dir, List<String> fileNameList) {
  135. File file = new File(dir);
  136. File[] tempList = file.listFiles();
  137. for (int i = 0; i < tempList.length; i++) {
  138. if (tempList[i].isFile()) {
  139. fileNameList.add(tempList[i].getName());
  140. } else if (tempList[i].isDirectory()) {
  141. getAllFileName(tempList[i].getAbsolutePath(), fileNameList);
  142. }
  143. }
  144. return fileNameList;
  145. }
  146. /**
  147. * 获取某个文件夹下的所有文件,包含文件夹和文件
  148. *
  149. * @param dir
  150. * @return
  151. */
  152. public static List<String> getAllFileName(String dir) {
  153. List<String> fileNameList = new ArrayList<>();
  154. return getAllFileName(dir, fileNameList);
  155. }
  156. /**
  157. * 删除文件,可以是单个文件或文件夹
  158. *
  159. * @param fileName 待删除的文件名
  160. * @return 文件删除成功返回true, 否则返回false
  161. */
  162. public static boolean deleteFileOrDirectory(String fileName) {
  163. File file = new File(fileName);
  164. if (!file.exists()) {
  165. return false;
  166. } else {
  167. if (file.isFile()) {
  168. return deleteFile(fileName);
  169. } else {
  170. return deleteDirectory(fileName);
  171. }
  172. }
  173. }
  174. /**
  175. * 删除单个文件
  176. *
  177. * @param fileName 被删除文件的文件名
  178. * @return 单个文件删除成功返回true, 否则返回false
  179. */
  180. public static boolean deleteFile(String fileName) {
  181. File file = new File(fileName);
  182. if (file.isFile() && file.exists()) {
  183. file.delete();
  184. return true;
  185. } else {
  186. return false;
  187. }
  188. }
  189. /**
  190. * 删除目录(文件夹)以及目录下的文件
  191. *
  192. * @param dir 被删除目录的文件路径
  193. * @return 目录删除成功返回true, 否则返回false
  194. */
  195. public static boolean deleteDirectory(String dir) {
  196. //如果dir不以文件分隔符结尾,自动添加文件分隔符
  197. if (!dir.endsWith(File.separator)) {
  198. dir = dir + File.separator;
  199. }
  200. File dirFile = new File(dir);
  201. //如果dir对应的文件不存在,或者不是一个目录,则退出
  202. if (!dirFile.exists() || !dirFile.isDirectory()) {
  203. return false;
  204. }
  205. boolean flag = true;
  206. //删除文件夹下的所有文件(包括子目录)
  207. File[] files = dirFile.listFiles();
  208. for (int i = 0; i < files.length; i++) {
  209. //删除子文件
  210. if (files[i].isFile()) {
  211. flag = deleteFile(files[i].getAbsolutePath());
  212. if (!flag) {
  213. break;
  214. }
  215. }
  216. //删除子目录
  217. else {
  218. flag = deleteDirectory(files[i].getAbsolutePath());
  219. if (!flag) {
  220. break;
  221. }
  222. }
  223. }
  224. if (!flag) {
  225. return false;
  226. }
  227. //删除当前目录
  228. if (dirFile.delete()) {
  229. return true;
  230. } else {
  231. return false;
  232. }
  233. }
  234. /**
  235. * 用于上传或复制文件
  236. *
  237. * @param srcFile 源文件
  238. * @param tarFile 目标文件
  239. * @throws IOException
  240. */
  241. public static void copyFile(File srcFile, File tarFile) throws IOException {
  242. InputStream inStream = new FileInputStream(srcFile);
  243. OutputStream outStream = new FileOutputStream(tarFile);
  244. byte[] buff = new byte[1024];
  245. int readed = -1;
  246. while ((readed = inStream.read(buff)) > 0) {
  247. outStream.write(buff, 0, readed);
  248. }
  249. outStream.flush();
  250. inStream.close();
  251. outStream.close();
  252. }
  253. /**
  254. * 文件的移动
  255. *
  256. * @param srcFile 源文件
  257. * @param tarFile 目标文件
  258. * @return
  259. */
  260. public static boolean moveTotherFolders(File srcFile, File tarFile) {
  261. return srcFile.renameTo(tarFile);
  262. }
  263. /**
  264. * 将文件的byte数组转换成目标文件
  265. *
  266. * @param srcByte 源文件数组
  267. * @param tarFile 目标文件
  268. * @throws IOException
  269. */
  270. public static File convertToFile(byte[] srcByte, File tarFile) throws IOException {
  271. //将字节转换成文件
  272. OutputStream outStream = new FileOutputStream(tarFile);
  273. outStream.write(srcByte);
  274. outStream.flush();
  275. outStream.close();
  276. return tarFile;
  277. }
  278. /**
  279. * 将文件的byte数组转换成目标文件
  280. *
  281. * @param inStream 源文件数组
  282. * @param tarFile 目标文件
  283. * @throws IOException
  284. */
  285. public static File convertToFile(InputStream inStream, File tarFile) throws IOException {
  286. if (inStream == null) return null;
  287. //将字节转换成文件
  288. OutputStream outStream = new FileOutputStream(tarFile);
  289. byte[] buff = new byte[1024];
  290. int readed = -1;
  291. while ((readed = inStream.read(buff)) > 0) {
  292. outStream.write(buff, 0, readed);
  293. }
  294. outStream.flush();
  295. inStream.close();
  296. outStream.close();
  297. return tarFile;
  298. }
  299. /**
  300. * 将文件转换成byte数组的形式
  301. *
  302. * @param srcFile 目标文件
  303. * @return byte数组
  304. * @throws IOException
  305. */
  306. public static byte[] converToByte(File srcFile) throws IOException {
  307. byte[] content = null;
  308. //转换成byte数组
  309. InputStream inStream = new FileInputStream(srcFile);
  310. if (inStream != null) {
  311. content = new byte[inStream.available()];
  312. inStream.read(content);
  313. inStream.close();
  314. }
  315. return content;
  316. }
  317. /**
  318. * 将文件转换成byte数组的形式
  319. *
  320. * @param inStream 目标文件
  321. * @return byte数组
  322. * @throws IOException
  323. */
  324. public static byte[] converToByte(InputStream inStream) throws IOException {
  325. byte[] content = null;
  326. //转换成byte数组
  327. if (inStream != null) {
  328. content = new byte[inStream.available()];
  329. inStream.read(content);
  330. inStream.close();
  331. }
  332. return content;
  333. }
  334. /**
  335. * 重命名文件
  336. *
  337. * @param fileName
  338. * @return
  339. */
  340. public static File renameFile(String filePath, String fileName) {
  341. filePath = filePath.endsWith(Constants.System.SLANT) ? filePath : filePath + Constants.System.SLANT;
  342. String oldFileName = filePath + fileName;
  343. File oldFile = new File(oldFileName);
  344. String newFileName = DateUtils.getCurrentTimestamp(DateUtils.DATETIME_17) + fileName;
  345. String newFilePath = filePath + newFileName;
  346. File newFile = new File(newFilePath);
  347. if (oldFile.exists() && oldFile.isFile()) {
  348. oldFile.renameTo(newFile);
  349. }
  350. return newFile;
  351. }
  352. /**
  353. * 重命名文件
  354. *
  355. * @param sourFile 源文件
  356. * @param tarFile 目标文件
  357. * @return
  358. */
  359. public static File renameFile(File sourFile, File tarFile) {
  360. sourFile.renameTo(tarFile);
  361. return tarFile;
  362. }
  363. /**
  364. * 多个斜杠转成一个斜杠
  365. *
  366. * @param path
  367. * @return
  368. */
  369. public static String transformPath(String path) {
  370. String regex = "/+";
  371. String regex1 = "\\+";
  372. return path.replaceAll(regex, "/").replaceAll(regex1, "/");
  373. }
  374. /**
  375. * 删除超时的文件
  376. *
  377. * @param tarFile
  378. * @param aLong
  379. */
  380. public static void deleteTimeoutFiles(File tarFile, Long aLong) {
  381. File[] files = tarFile.listFiles();
  382. Arrays.stream(files).forEach(file -> {
  383. Long ftime = file.lastModified();
  384. if (ftime < aLong) {
  385. deleteFile(file.getAbsolutePath());
  386. }
  387. });
  388. }
  389. /**
  390. * 将传入的二进制数组,获取文件头部对应的二进制信息
  391. *
  392. * @param src 二进制数组
  393. * @return 二进制信息
  394. * @throws Exception
  395. */
  396. public static String bytesToHexString(byte[] src) throws Exception {
  397. StringBuilder stringBuilder = new StringBuilder();
  398. if (src == null || src.length <= 0) {
  399. return null;
  400. }
  401. for (int i = 0; i < src.length; i++) {
  402. int v = src[i] & 0xFF;
  403. String hv = Integer.toHexString(v);
  404. if (hv.length() < 2) {
  405. stringBuilder.append(0);
  406. }
  407. stringBuilder.append(hv);
  408. }
  409. return stringBuilder.toString();
  410. }
  411. /**
  412. * 根据传入的文件取得对应的文件类型
  413. *
  414. * @param file 文件对应的信息
  415. * @return 文件类型
  416. */
  417. public static String[] getFileType(File file) throws Exception {
  418. return getFileType(getFileContent(file));
  419. }
  420. /**
  421. * 根据传入的文件流取得对应的文件类型
  422. *
  423. * @param is 文件流
  424. * @return 文件类型
  425. */
  426. public static String[] getFileType(InputStream is) throws Exception {
  427. return getFileType(getFileContent(is));
  428. }
  429. /**
  430. * 根据文件字节取得对应的文件类型
  431. *
  432. * @param srcByte 文件字节
  433. * @return 文件类型
  434. */
  435. public static String[] getFileType(byte[] srcByte) throws Exception {
  436. return getFileType(getFileContent(srcByte));
  437. }
  438. /**
  439. * 根据传入的头部二进制信息获取文件类型
  440. *
  441. * @param fileContent 头部二进制信息
  442. * @return 文件类型
  443. * @throws Exception
  444. */
  445. public static String[] getFileType(String fileContent) throws Exception {
  446. //取得文件头对应的二进制数组
  447. Map<String, String[]> map = getFileSuffixMap();
  448. String[] fileType = null;
  449. //便利文件取得对应的文件类型
  450. if (fileContent != null) {
  451. for (String key : map.keySet()) {
  452. if (fileContent.toLowerCase().startsWith(key.toLowerCase())) {
  453. fileType = map.get(key);
  454. break;
  455. }
  456. }
  457. }
  458. return fileType;
  459. }
  460. /**
  461. * 根据传入的文件取得文件头部的二进制信息
  462. *
  463. * @param file 文件类型
  464. * @return 二进制信息
  465. * @throws Exception
  466. */
  467. public static String getFileContent(File file) throws Exception {
  468. return getFileContent(new FileInputStream(file));
  469. }
  470. /**
  471. * 从流中读出前28位字节,再得到文件头信息
  472. *
  473. * @param is InputStream对象
  474. * @return 文件头2进制数组
  475. * @throws IOException
  476. */
  477. public static String getFileContent(InputStream is) throws Exception {
  478. byte[] b = new byte[28];
  479. try {
  480. //取得28位文件头
  481. is.read(b, 0, 28);
  482. } catch (Exception e) {
  483. e.printStackTrace();
  484. } finally {
  485. try {
  486. if (is != null) is.close();
  487. } catch (Exception e) {
  488. e.printStackTrace();
  489. }
  490. }
  491. return getFileContent(b);
  492. }
  493. /**
  494. * 截取二进制数组的前28位,在获得对应的文件头二进制数组信息
  495. *
  496. * @param srcByte 传入的二进制数组
  497. * @return 文件头二进制数组信息
  498. * @throws Exception
  499. */
  500. private static String getFileContent(byte[] srcByte) throws Exception {
  501. String content = null;
  502. if (srcByte != null && srcByte.length > 0) {
  503. //如果二进制文件的长度大于28位,则截取前28位
  504. byte[] b = new byte[28];
  505. if (srcByte.length > 28) System.arraycopy(srcByte, 0, b, 0, 28);
  506. else b = srcByte;
  507. //取得后最文件
  508. content = bytesToHexString(b);
  509. }
  510. return content;
  511. }
  512. /**
  513. * 取得文件后缀对应的字符串,前4个组成的文件头
  514. *
  515. * @return 文件头对应的后缀
  516. */
  517. public static Map<String, String[]> getFileSuffixMap() {
  518. //设置接收参数对应的MAP
  519. Map<String, String[]> map = new HashMap<String, String[]>();
  520. //设置对应的值
  521. map.put("FFD8FF", new String[]{"JPEG"});
  522. map.put("89504E47", new String[]{"PNG"});
  523. map.put("47494638", new String[]{"GIF"});
  524. map.put("49492A00", new String[]{"TIFF"});
  525. map.put("424D", new String[]{"BMP"});
  526. map.put("41433130", new String[]{"DWG"});
  527. map.put("38425053", new String[]{"PSD"});
  528. map.put("7B5C727466", new String[]{"RTF"});
  529. map.put("3C3F786D6C", new String[]{"XML"});
  530. map.put("68746D6C3E", new String[]{"HTML"});
  531. map.put("44656C69766572792D646174653A", new String[]{"EML"});
  532. map.put("CFAD12FEC5FD746F", new String[]{"DBX"});
  533. map.put("2142444E", new String[]{"PST"});
  534. map.put("D0CF11E0", new String[]{"XLS", "DOC"});
  535. map.put("5374616E64617264204A", new String[]{"MDB"});
  536. map.put("FF575043", new String[]{"WPD"});
  537. map.put("252150532D41646F6265", new String[]{"EPS"});
  538. map.put("255044462D312E", new String[]{"PDF"});
  539. map.put("AC9EBD8F", new String[]{"QDF"});
  540. map.put("E3828596", new String[]{"PWL"});
  541. map.put("504B0", new String[]{"XLSX", "ZIP"});
  542. map.put("52617221", new String[]{"RAR"});
  543. map.put("57415645", new String[]{"WAV"});
  544. map.put("41564920", new String[]{"AVI"});
  545. map.put("2E7261FD", new String[]{"RAM"});
  546. map.put("2E524D46", new String[]{"RM"});
  547. map.put("000001BA", new String[]{"MPG"});
  548. map.put("6D6F6F76", new String[]{"MOV"});
  549. map.put("3026B2758E66CF11", new String[]{"ASF"});
  550. map.put("4D546864", new String[]{"MID"});
  551. map.put("494433", new String[]{"MP3"});
  552. map.put("61646661647366", new String[]{"TXT"});
  553. map.put("202f2a2a", new String[]{"TXT"});
  554. return map;
  555. }
  556. /**
  557. * 解析txt文档
  558. *
  559. * @param txtFile txt文件
  560. * @return
  561. */
  562. public static List<List<String>> parseTxt(String txtFile, String separator) {
  563. if (txtFile == null) {
  564. return null;
  565. }
  566. List<List<String>> data = new ArrayList<List<String>>();
  567. try {
  568. BufferedReader buffReader = null;
  569. FileInputStream fi = new FileInputStream(txtFile);
  570. String carSet = getTxtFileCharSet(new File(txtFile));
  571. System.out.println(carSet);
  572. if ("Unicode".equals(carSet)) {
  573. buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-16"));
  574. } else if ("Unicode big endian".equals(carSet)) {
  575. buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-16LE"));
  576. } else {
  577. buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-8"));
  578. }
  579. System.out.println(Charset.defaultCharset().name());
  580. String line = "";
  581. while (buffReader.ready()) {
  582. line = buffReader.readLine();
  583. if (StringUtils.isBlank(line)) continue;
  584. String[] chars = line.split(separator);
  585. List<String> innerData = new ArrayList<String>();
  586. for (String charactor : chars) {
  587. if (StringUtils.isNotBlank(charactor)) {
  588. if ("UTF-8 + BOM".equals(carSet)) {
  589. charactor = new String(charactor.getBytes(Charset.defaultCharset().name()), "UTF-8");
  590. charactor = charactor.indexOf("?") == 0 ? charactor.substring(1) : charactor;
  591. }
  592. }
  593. innerData.add(charactor);
  594. }
  595. data.add(innerData);
  596. }
  597. if (buffReader != null) {
  598. buffReader.close();
  599. buffReader = null;
  600. }
  601. if (fi != null) {
  602. fi.close();
  603. fi = null;
  604. }
  605. } catch (Exception e) {
  606. e.printStackTrace();
  607. }
  608. return data;
  609. }
  610. /**
  611. * 查看文件编码
  612. *
  613. * @param file
  614. * @return
  615. */
  616. public static String getTxtFileCharSet(File file) {
  617. try {
  618. return getTxtFileCharSet(new FileInputStream(file));
  619. } catch (FileNotFoundException e) {
  620. e.printStackTrace();
  621. return "";
  622. }
  623. }
  624. /**
  625. * 查看TXT文件编码
  626. *
  627. * @param inputStream
  628. * @return
  629. */
  630. public static String getTxtFileCharSet(InputStream inputStream) {
  631. String carSet = "ANSI";
  632. try {
  633. byte[] fileHead = new byte[3];
  634. inputStream.read(fileHead);
  635. if (-17 == fileHead[0] && -69 == fileHead[1] && -65 == fileHead[2]) {
  636. carSet = "UTF-8 + BOM";
  637. } else if (49 == fileHead[0] && 51 == fileHead[1] && 49 == fileHead[2]) {
  638. carSet = "UTF-8";
  639. } else if (-1 == fileHead[0] && -2 == fileHead[1]) {
  640. carSet = "Unicode";
  641. } else if (-2 == fileHead[0] && -1 == fileHead[1]) {
  642. carSet = "Unicode big endian";
  643. }
  644. } catch (Exception e) {
  645. e.printStackTrace();
  646. } finally {
  647. if (inputStream != null) {
  648. try {
  649. inputStream.close();
  650. inputStream = null;
  651. } catch (IOException e) {
  652. e.printStackTrace();
  653. }
  654. }
  655. }
  656. return carSet;
  657. }
  658. /**
  659. * 写入Txt
  660. *
  661. * @param path
  662. * @param txt
  663. * @throws IOException
  664. */
  665. public static boolean writeFile(String path, String txt) {
  666. // 相对路径,如果没有则要建立一个新的path文件
  667. File file = new File(path);
  668. try {
  669. // 创建新文件
  670. createNewFile(file.getAbsolutePath());
  671. // 字符缓冲输出流:写东西到该文件
  672. BufferedWriter out = new BufferedWriter(new FileWriter(file));
  673. // 写东西:\r\n即为换行
  674. out.write(txt);
  675. // 把缓存区内容压入文件
  676. out.flush();
  677. // 最后关闭流
  678. out.close();
  679. //返回成功
  680. return true;
  681. } catch (IOException e) {
  682. e.printStackTrace();
  683. return false;
  684. }
  685. }
  686. /**
  687. * 描述: 获取格式化的文件大小
  688. * 格式为带单位保留一位小数
  689. *
  690. * @param size
  691. * @return
  692. */
  693. public static String getFormatSize(double size) {
  694. String fileSizeString = "";
  695. if (size < 1024) {
  696. fileSizeString = decimalFormat.format(size) + B_UNIT;
  697. } else if (size < 1048576) {
  698. fileSizeString = decimalFormat.format(size / 1024) + KB_UNIT;
  699. } else if (size < 1073741824) {
  700. fileSizeString = decimalFormat.format(size / 1048576) + MB_UNIT;
  701. } else {
  702. fileSizeString = decimalFormat.format(size / 1073741824) + GB_UNIT;
  703. }
  704. return fileSizeString;
  705. }
  706. /**
  707. * 获取文件大小
  708. *
  709. * @param size
  710. * @return
  711. */
  712. public static String getFormatSize(long size) {
  713. return getFormatSize((double) size);
  714. }
  715. /**
  716. * 传文件全路径,解压gz文件到当前文件夹
  717. *
  718. * @param fileUrl
  719. * @return
  720. */
  721. public static String unGzFile(String fileUrl) {
  722. String errMess="";
  723. GZIPInputStream in = null;
  724. try {
  725. in = new GZIPInputStream(new FileInputStream(fileUrl));
  726. } catch(FileNotFoundException e) {
  727. log.info("File not found. " + fileUrl);
  728. errMess=e.getMessage();
  729. } catch (IOException e) {
  730. e.printStackTrace();
  731. errMess=e.getMessage();
  732. }
  733. String gzFileNameAndUrl = getGzFileNameAndUrl(fileUrl);
  734. FileOutputStream out = null;
  735. try {
  736. out = new FileOutputStream(gzFileNameAndUrl);
  737. } catch (FileNotFoundException e) {
  738. log.info("Could not write to file. " + gzFileNameAndUrl);
  739. errMess=e.getMessage();
  740. }
  741. log.info("文件路径=========" + gzFileNameAndUrl);
  742. try {
  743. byte[] buf = new byte[1024];
  744. int len;
  745. while((len = in.read(buf)) > 0) {
  746. out.write(buf, 0, len);
  747. }
  748. in.close();
  749. out.close();
  750. deleteFileOrDirectory(fileUrl);
  751. } catch (IOException e) {
  752. e.printStackTrace();
  753. errMess=e.getMessage();
  754. }
  755. return errMess;
  756. }
  757. /**
  758. * 传文件全路径,解压zip文件到当前文件夹
  759. *
  760. * @param filePath
  761. * @return
  762. */
  763. public static String unzipFile(String filePath) {
  764. String errMess="";
  765. String zipDir = filePath.substring(0,filePath.lastIndexOf("/") + 1);
  766. String name = "";
  767. try {
  768. BufferedOutputStream dest = null;
  769. BufferedInputStream is = null;
  770. ZipEntry entry;
  771. ZipFile zipfile = new ZipFile(filePath, Charset.forName("GBK"));
  772. Enumeration dir = zipfile.entries();
  773. while (dir.hasMoreElements()){
  774. entry = (ZipEntry) dir.nextElement();
  775. if( entry.isDirectory()){
  776. name = entry.getName();
  777. name = name.substring(0, name.length() - 1);
  778. File fileObject = new File(zipDir + name);
  779. fileObject.mkdir();
  780. }
  781. }
  782. Enumeration e = zipfile.entries();
  783. while (e.hasMoreElements()) {
  784. entry = (ZipEntry) e.nextElement();
  785. if( entry.isDirectory()){
  786. continue;
  787. }else{
  788. is = new BufferedInputStream(zipfile.getInputStream(entry));
  789. int count;
  790. byte[] dataByte = new byte[1024];
  791. FileOutputStream fos = new FileOutputStream(zipDir+entry.getName());
  792. dest = new BufferedOutputStream(fos, 1024);
  793. while ((count = is.read(dataByte, 0, 1024)) != -1) {
  794. dest.write(dataByte, 0, count);
  795. }
  796. dest.flush();
  797. dest.close();
  798. is.close();
  799. }
  800. }
  801. deleteFileOrDirectory(filePath);
  802. } catch (Exception e) {
  803. e.printStackTrace();
  804. errMess=e.getMessage();
  805. }
  806. return errMess;
  807. }
  808. /**
  809. * 传路径,找出当前路径下所有子目录以及文件
  810. *
  811. * @param
  812. * @return
  813. */
  814. public static List<String> findUnzipAllFile(File filePath,List<String> filePaths) {
  815. File[] files = filePath.listFiles();
  816. if(files == null){
  817. return filePaths;
  818. }
  819. for(File f:files){
  820. if(f.isDirectory()){
  821. filePaths.add(f.getPath());
  822. findUnzipAllFile(f,filePaths);
  823. }else{
  824. filePaths.add(f.getPath());
  825. }
  826. }
  827. return filePaths;
  828. }
  829. /**
  830. * 截取文件后缀
  831. *
  832. * @param
  833. * @return
  834. */
  835. public static String checkFile(String filePaths) {
  836. String hzhwjm = "";
  837. String houZui = "";
  838. int i =filePaths.lastIndexOf("/");
  839. if (i > 0 && i < filePaths.length() - 1) {
  840. hzhwjm = filePaths.substring(i + 1);
  841. }
  842. int j =hzhwjm.lastIndexOf(".");
  843. if (j > 0 && j < hzhwjm.length() - 1) {
  844. houZui = hzhwjm.substring( j+ 1);
  845. }
  846. if(houZui.equals("gz")||houZui.equals("GZ")){
  847. if(j>3){
  848. if(hzhwjm.substring(j - 3).equals("tar.gz")||hzhwjm.substring(j - 3).equals("TAR.GZ")){
  849. houZui=hzhwjm.substring(j - 3);
  850. }
  851. }
  852. }
  853. return houZui;
  854. }
  855. public static String getGzFileNameAndUrl(String f) {
  856. String fname = "";
  857. int i = f.lastIndexOf('.');
  858. if (i > 0 && i < f.length() - 1) {
  859. fname = f.substring(0,i);
  860. }
  861. return fname;
  862. }
  863. /**
  864. * 压缩文件通过文件全路径截取文件名
  865. *
  866. * @param
  867. * @return
  868. */
  869. public static String getFileNameByAllUrl(String fileAllUrl) {
  870. String fName = "";
  871. int i = fileAllUrl.lastIndexOf('/');
  872. if (i > 0 && i < fileAllUrl.length() - 1) {
  873. fName = fileAllUrl.substring(i+1);
  874. }
  875. return fName;
  876. }
  877. /**
  878. * 压缩文件通过文件全路径截取文件路径
  879. *
  880. * @param
  881. * @return
  882. */
  883. public static String getFileUrlByAllUrl(String fileAllUrl) {
  884. String fUrl = "";
  885. int i = fileAllUrl.lastIndexOf('/');
  886. if (i > 0 && i < fileAllUrl.length() - 1) {
  887. fUrl = fileAllUrl.substring(0,i+1);
  888. }
  889. return fUrl;
  890. }
  891. /**
  892. * 解压tar.gz 传文件全路径
  893. * @param filePath
  894. *
  895. */
  896. public static String unTarGz(String filePath) throws IOException{
  897. String outputDir = filePath.substring(0,filePath.lastIndexOf("/") + 1);
  898. String errMess="";
  899. File file = new File(filePath);
  900. TarInputStream tarIn = null;
  901. try{
  902. tarIn = new TarInputStream(new GZIPInputStream(
  903. new BufferedInputStream(new FileInputStream(file))),
  904. 1024 * 2);
  905. createDirectory(outputDir,null);//创建输出目录
  906. TarEntry entry = null;
  907. while( (entry = tarIn.getNextEntry()) != null ){
  908. if(entry.isDirectory()){//是目录
  909. entry.getName();
  910. createDirectory(outputDir,entry.getName());//创建空目录
  911. }else{//是文件
  912. File tmpFile = new File(outputDir + "/" + entry.getName());
  913. createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
  914. OutputStream out = null;
  915. try{
  916. out = new FileOutputStream(tmpFile);
  917. int length = 0;
  918. byte[] b = new byte[2048];
  919. while((length = tarIn.read(b)) != -1){
  920. out.write(b, 0, length);
  921. }
  922. }catch(IOException ex){
  923. errMess=ex.getMessage();
  924. throw ex;
  925. }finally{
  926. if(out!=null)
  927. out.close();
  928. }
  929. }
  930. }
  931. }catch(IOException ex){
  932. errMess=ex.getMessage();
  933. throw new IOException("解压归档文件出现异常",ex);
  934. } finally{
  935. try{
  936. if(tarIn != null){
  937. tarIn.close();
  938. }
  939. }catch(IOException ex){
  940. errMess=ex.getMessage();
  941. throw new IOException("关闭tarFile出现异常",ex);
  942. }
  943. }
  944. deleteFileOrDirectory(filePath);
  945. return errMess;
  946. }
  947. /**
  948. * 构建目录
  949. * @param outputDir
  950. * @param subDir
  951. */
  952. public static void createDirectory(String outputDir,String subDir){
  953. File file = new File(outputDir);
  954. if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
  955. file = new File(outputDir + "/" + subDir);
  956. }
  957. if(!file.exists()){
  958. if(!file.getParentFile().exists())
  959. file.getParentFile().mkdirs();
  960. file.mkdirs();
  961. }
  962. }
  963. /**
  964. * 解析txt删除第一行字段
  965. * @param fileName
  966. *
  967. */
  968. public static void removeFirstLine(String fileName) throws IOException {
  969. RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
  970. long writePosition = raf.getFilePointer();
  971. raf.readLine();
  972. long readPosition = raf.getFilePointer();
  973. byte[] buff = new byte[1024];
  974. int n;
  975. while (-1 != (n = raf.read(buff))) {
  976. raf.seek(writePosition);
  977. raf.write(buff, 0, n);
  978. readPosition += n;
  979. writePosition += n;
  980. raf.seek(readPosition);
  981. }
  982. raf.setLength(writePosition);
  983. raf.close();
  984. }
  985. }
  986. package com.fyg.common.constants;
  987. public final class Constants {
  988. /**
  989. * code码
  990. */
  991. public static final class Code {
  992. /**
  993. * 成功 success
  994. */
  995. public static final String SUCCESS = "00";
  996. /**
  997. * 参数不正确
  998. */
  999. public static final String PARAM_INVALID = "01";
  1000. /**
  1001. * 文件下载
  1002. */
  1003. public static final String FILE_DOWNLOAD_FILE = "96";
  1004. /**
  1005. * 上传文件超过限制
  1006. */
  1007. public static final String FILE_UPLOAD_FILE_MAX = "97";
  1008. /**
  1009. * 文件上传
  1010. */
  1011. public static final String FILE_UPLOAD = "98";
  1012. /**
  1013. * 系统异常
  1014. */
  1015. public static final String UNKNOW_ERROR = "99";
  1016. /**
  1017. * 未登录不通过
  1018. */
  1019. public static final String NO_LOGIN = "02";
  1020. /**
  1021. * 数据重复
  1022. */
  1023. public static final String DATA_REPEAT = "03";
  1024. }
  1025. /**
  1026. * code 码提示信息
  1027. */
  1028. public static final class Message {
  1029. /**
  1030. * 成功 success(00)
  1031. */
  1032. public static final String SUCCESS = "success";
  1033. /**
  1034. * 上传文件超过限制
  1035. */
  1036. public static final String FILE_UPLOAD_FILE_MAX = "upload file is failed, %s";
  1037. /**
  1038. * 下载文件错误
  1039. */
  1040. public static final String FILE_DOWNLOAD_FILE = "download file is failed, %s";
  1041. /**
  1042. * 文件上传错误(98)
  1043. */
  1044. public static final String FILE_UPLOAD = "The file cannot be empty, please contact the administrator!";
  1045. /**
  1046. * 错误信息(99)
  1047. */
  1048. public static final String UNKNOW_ERROR = "system problem, please contact administrator!";
  1049. /**
  1050. * 未登录提示信息(02)
  1051. */
  1052. public static final String NO_LOGIN = "未登录或登录已超时,请登录!!!";
  1053. /**
  1054. * 数据重复
  1055. */
  1056. public static final String DATA_REPEAT = "该数据已存在,请勿重复提交!";
  1057. }
  1058. /**
  1059. * 系统常量
  1060. */
  1061. public static final class System {
  1062. /**
  1063. * /
  1064. */
  1065. public static final String SLANT = "/";
  1066. /**
  1067. * \
  1068. */
  1069. public static final String UNSLANT = "\\";
  1070. /**
  1071. * ,
  1072. */
  1073. public static final String COMMA = ",";
  1074. /**
  1075. * 空字符串("")empty
  1076. */
  1077. public static final String EMPTY = "";
  1078. /**
  1079. * " "
  1080. */
  1081. public static final String SPACE = " ";
  1082. /**
  1083. * .
  1084. */
  1085. public static final String SPOT = ".";
  1086. /**
  1087. * :
  1088. */
  1089. public static final String COLON = ":";
  1090. /**
  1091. * (string *)
  1092. */
  1093. public static final String ASTERISK = "*";
  1094. /**
  1095. * (string ?)
  1096. */
  1097. public static final String ASK = "?";
  1098. /**
  1099. * -
  1100. */
  1101. public static final String TRANSVERSE = "-";
  1102. /**
  1103. * ;
  1104. */
  1105. public static final String SEMICOLON = ";";
  1106. /**
  1107. * |
  1108. */
  1109. public static final String STRAIGHT = "|";
  1110. /**
  1111. * _
  1112. */
  1113. public static final String UNDERLINE = "_";
  1114. /**
  1115. * UTF-8
  1116. */
  1117. public static final String UTF8 = "UTF-8";
  1118. /**
  1119. * GBK
  1120. */
  1121. public static final String GBK = "GBK";
  1122. /**
  1123. * ISO-8859-1
  1124. */
  1125. public static final String ISO88591 = "ISO-8859-1";
  1126. /**
  1127. * url 地址参数连接符(&)
  1128. */
  1129. public static final String AND = "&";
  1130. /**
  1131. * 等于(=)
  1132. */
  1133. public static final String EQUAL = "=";
  1134. /**
  1135. * 艾特(@)
  1136. */
  1137. public static final String AT = "@";
  1138. }
  1139. public static final class ID {
  1140. /**
  1141. * 用户ID前缀
  1142. */
  1143. public static final String ID_USER = "USER";
  1144. /**
  1145. * 角色ID前缀
  1146. */
  1147. public static final String ID_ROLE = "ROLE";
  1148. /**
  1149. * 菜单ID前缀
  1150. */
  1151. public static final String ID_MENU = "MENU";
  1152. /**
  1153. * 附件ID前缀
  1154. */
  1155. public static final String ID_FILE = "FILE";
  1156. }
  1157. public static final class Web {
  1158. /**
  1159. * 登录类型(随机码)
  1160. */
  1161. public static final String LOGIN_TYPE_CODE = "code";
  1162. /**
  1163. * 登录类型(密码)
  1164. */
  1165. public static final String LOGIN_TYPE_PASSWORD = "password";
  1166. /**
  1167. * 电话
  1168. */
  1169. public static final String PHONE = "phone";
  1170. /**
  1171. * 邮箱
  1172. */
  1173. public static final String EMAIL = "email";
  1174. /**
  1175. * web端
  1176. */
  1177. private static final String PROJECT = "web";
  1178. /**
  1179. * 在线用户
  1180. */
  1181. public static final String ONLINE_USER = "online.user";
  1182. /**
  1183. * 令牌
  1184. */
  1185. public static final String TOKEN = "TOKEN";
  1186. /**
  1187. * 用户登录session key
  1188. */
  1189. public static final String SESSION_USER = PROJECT + ".manager.session.user";
  1190. }
  1191. /**
  1192. * redis key
  1193. */
  1194. public static final class Redis {
  1195. /**
  1196. * 所有配置项
  1197. */
  1198. public static final String CONFIG_ALL = Web.PROJECT + ":db:config:";
  1199. /**
  1200. * 检测是否登录的例外地址配置
  1201. */
  1202. public static final String REQUEST_CONFIG = CONFIG_ALL + "page.login.notcheck";
  1203. /**
  1204. * 用户
  1205. */
  1206. public static final String USER_USER = Web.PROJECT + ":login:user:user:";
  1207. /**
  1208. * 用户、角色
  1209. */
  1210. public static final String USER_ROLE = Web.PROJECT + ":login:user:role:";
  1211. /**
  1212. * 角色
  1213. */
  1214. public static final String ROLE_ROLE = Web.PROJECT + ":login:role:role:";
  1215. /**
  1216. * 角色、菜单
  1217. */
  1218. public static final String ROLE_MENU = Web.PROJECT + ":login:role:menu:";
  1219. /**
  1220. * 菜单
  1221. */
  1222. public static final String MENU_MENU = Web.PROJECT + ":login:menu:menu:";
  1223. /**
  1224. * 组织
  1225. */
  1226. public static final String ORGAN_ORGAN = Web.PROJECT + ":login:organ:organ:";
  1227. /**
  1228. * 组织、角色
  1229. */
  1230. public static final String ORGAN_ROLE = Web.PROJECT + ":login:organ:role:";
  1231. /**
  1232. * 令牌
  1233. */
  1234. public static final String TOKEN = Web.PROJECT + ":token:";
  1235. }
  1236. public static final class OpsLogType {
  1237. /**
  1238. * 添加
  1239. */
  1240. public static final String ADD = "ADD";
  1241. /**
  1242. * 修改
  1243. */
  1244. public static final String UPDATE = "UPDATE";
  1245. /**
  1246. * 删除
  1247. */
  1248. public static final String DELETE = "DELETE";
  1249. /**
  1250. * 查询
  1251. */
  1252. public static final String SELECT = "SELECT";
  1253. /**
  1254. * 设置
  1255. */
  1256. public static final String SET = "SET";
  1257. /**
  1258. * 重置
  1259. */
  1260. public static final String RESET = "RESET";
  1261. /**
  1262. * 停用
  1263. */
  1264. public static final String STOP = "STOP";
  1265. /**
  1266. * 上传
  1267. */
  1268. public static final String UPLOAD = "UPLOAD";
  1269. /**
  1270. * 下载
  1271. */
  1272. public static final String DOWNLOAD = "DOWNLOAD";
  1273. /**
  1274. * 登陆
  1275. */
  1276. public static final String LOGIN = "LOGIN";
  1277. /**
  1278. * 退出
  1279. */
  1280. public static final String LOGINOUT = "LOGINOUT";
  1281. }
  1282. }

在 Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象,也就是说,如果希望在程序中操作文件和目录,则都可以通过 File 类来完成。File 类定义了一些方法来操作文件,如新建、删除、重命名文件和目录等。

File 类不能访问文件内容本身,如果需要访问文件内容本身,则需要使用输入/输出流。

File 类提供了如下三种形式构造方法。

  1. File(String path):如果 path 是实际存在的路径,则该 File 对象表示的是目录;如果 path 是文名,则该 File 对象表示的是文件。

  2. File(String path, String name):path 是路径名,name 是文件名。

  3. File(File dir, String name):dir 是路径对象,name 是文件名。

Java IO流是既可以从中读取,也可以写入到其中的数据流。正如这个系列教程之前提到过的,流通常会与数据源、数据流向目的地相关联,比如文件、网络等等。

流和数组不一样,不能通过索引读写数据。在流中,你也不能像数组那样前后移动读取数据,除非使用RandomAccessFile 处理文件。流仅仅只是一个连续的数据流。

某些类似PushbackInputStream 流的实现允许你将数据重新推回到流中,以便重新读取。然而你只能把有限的数据推回流中,并且你不能像操作数组那样随意读取数据。流中的数据只能够顺序访问。

Java IO流通常是基于字节或者基于字符的。字节流通常以“stream”命名,比如InputStream和OutputStream。除了DataInputStream 和DataOutputStream 还能够读写int, long, float和double类型的值以外,其他流在一个操作时间内只能读取或者写入一个原始字节。

字符流通常以“Reader”或者“Writer”命名。字符流能够读写字符(比如Latin1或者Unicode字符)。可以浏览Java Readers and Writers获取更多关于字符流输入输出的信息。

InputStream

java.io.InputStream类是所有Java IO输入流的基类。如果你正在开发一个从流中读取数据的组件,请尝试用InputStream替代任何它的子类(比如FileInputStream)进行开发。这么做能够让你的代码兼容任何类型而非某种确定类型的输入流。

然而仅仅依靠InputStream并不总是可行。如果你需要将读过的数据推回到流中,你必须使用PushbackInputStream,这意味着你的流变量只能是这个类型,否则在代码中就不能调用PushbackInputStream的unread()方法。

通常使用输入流中的read()方法读取数据。read()方法返回一个整数,代表了读取到的字节的内容(译者注:0 ~ 255)。当达到流末尾没有更多数据可以读取的时候,read()方法返回-1。

发表评论

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

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

相关阅读

    相关 java读取文件写入文件

    Java 中 IO 流 Java 中 IO 流分为几种? 按照流的流向分,可以分为输入流和输出流; 按照操作单元划分,可以划分为字节流和字符流; 按照流的角色划分为节点