java文件读写--工具方法

蔚落 2023-01-10 14:56 258阅读 0赞
  1. package util;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import org.springframework.util.StringUtils;
  11. public class FileUtil {
  12. /**
  13. * @Title: writeFileByLines
  14. * @Description: 按行写文件
  15. * @param fileName
  16. * @param strs
  17. * @param append 是否追加
  18. * @throws IOException
  19. * @date: 2021-01-25 12:32
  20. */
  21. public static void writeFileByLines(String fileName, String[] strs, boolean append) throws IOException {
  22. FileWriter fw = new FileWriter(fileName, append);
  23. for (String str : strs) {
  24. fw.write(str);
  25. fw.write("\n");//换行
  26. }
  27. fw.flush();
  28. fw.close();
  29. }
  30. /**
  31. * @Title: readFile
  32. * @Description: 读取文件内容
  33. * @param filePathAndName 绝对路径
  34. * @param encoding 编码格式
  35. * @return String
  36. * @date: 2021-01-25 12:39
  37. */
  38. public static String readFile(String filePathAndName,String encoding) {
  39. String fileContent = "";
  40. try {
  41. if (StringUtils.isEmpty(encoding)) {
  42. encoding = "UTF-8";
  43. }
  44. File f = new File(filePathAndName);
  45. if (f.isFile() && f.exists()) {
  46. InputStreamReader read = new InputStreamReader(new FileInputStream(f), encoding);
  47. BufferedReader reader = new BufferedReader(read);
  48. String line;
  49. while ((line = reader.readLine()) != null) {
  50. fileContent += line;
  51. }
  52. read.close();
  53. }
  54. } catch (Exception e) {
  55. System.out.println("读取文件内容操作出错");
  56. e.printStackTrace();
  57. }
  58. return fileContent;
  59. }
  60. /**
  61. * @Title: readTxtFileToListString
  62. * @Description: 读取txt文本文件
  63. * @param filePath
  64. * @param encoding 编码格式
  65. * @return List<String>
  66. * @date: 2021-01-25 12:32
  67. */
  68. public static List<String> readTxtFileToListString(String filePath, String encoding) {
  69. List<String> listContent = new ArrayList<>();
  70. try {
  71. if (StringUtils.isEmpty(encoding)) {
  72. encoding = "UTF-8";
  73. }
  74. File file = new File(filePath);
  75. if (file.isFile() && file.exists()) { // 判断文件是否存在
  76. InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
  77. BufferedReader bufferedReader = new BufferedReader(read);
  78. String lineTxt = null;
  79. while ((lineTxt = bufferedReader.readLine()) != null) {
  80. // System.out.println(lineTxt);
  81. listContent.add(lineTxt);
  82. }
  83. read.close();
  84. } else {
  85. System.out.println("找不到指定的文件");
  86. }
  87. } catch (Exception e) {
  88. System.out.println("读取文件内容出错");
  89. e.printStackTrace();
  90. }
  91. return listContent;
  92. }
  93. }

发表评论

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

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

相关阅读