From f5271b058bf03f87ff2a719ab288f09b8887897d Mon Sep 17 00:00:00 2001 From: Aborn Jiang Date: Wed, 30 Jun 2021 11:59:27 +0800 Subject: [PATCH] add FileUtils --- pom.xml | 8 +++ .../com/github/aborn/tools/StringTools.java | 8 ++- .../com/github/aborn/utils/FileUtils.java | 65 +++++++++++++++++++ 3 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/aborn/utils/FileUtils.java diff --git a/pom.xml b/pom.xml index af5c27f..52d0b95 100644 --- a/pom.xml +++ b/pom.xml @@ -8,6 +8,14 @@ CodeSnippet 1.0-SNAPSHOT + + + org.apache.commons + commons-lang3 + 3.3.1 + + + 8 8 diff --git a/src/main/java/com/github/aborn/tools/StringTools.java b/src/main/java/com/github/aborn/tools/StringTools.java index 349d6ac..e82bfc0 100644 --- a/src/main/java/com/github/aborn/tools/StringTools.java +++ b/src/main/java/com/github/aborn/tools/StringTools.java @@ -1,5 +1,7 @@ package com.github.aborn.tools; +import com.github.aborn.utils.FileUtils; + import java.util.ArrayList; import java.util.List; @@ -35,12 +37,14 @@ public class StringTools { /** * 对邮件里的内容获取 - * TODO 从文件中读取内容 - * * @param args */ public static void main(String[] args) { String inputValue = "zhangsan ; lisi ; "; + String fileName = "/Users/aborn/temp/t.txt"; + String fileContent = FileUtils.read(fileName); System.out.println(getEmailNameInfo(inputValue)); + System.out.println("\n"); + System.out.println(getEmailNameInfo(fileContent)); } } diff --git a/src/main/java/com/github/aborn/utils/FileUtils.java b/src/main/java/com/github/aborn/utils/FileUtils.java new file mode 100644 index 0000000..0cc4570 --- /dev/null +++ b/src/main/java/com/github/aborn/utils/FileUtils.java @@ -0,0 +1,65 @@ +package com.github.aborn.utils; + +import java.io.*; + +import org.apache.commons.lang3.StringUtils; + +/** + * @author aborn + * @date 2021/06/30 11:43 AM + */ +public class FileUtils { + + public static void main(String[] args) { + String file = "/Users/aborn/temp/t.txt"; + System.out.println(read(file)); + } + + /** + * Read file content as string, + * null if file doesn't exist or read exception + * + * @param fileName 文件名全路径 + * @return file content + */ + public static String read(String fileName) { + if (StringUtils.isBlank(fileName)) { + return null; + } + + File file = new File(fileName); + if (!file.exists()) { + return null; + } + + // 再从文件里读 + InputStream inputStream = null; + try { + inputStream = new FileInputStream(file); + // 临时存储 bitSet的 array信息 + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 缓冲区大小 + int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + int n; + // 读取到buffer缓冲区,缓冲区大小为bufferSize + while ((n = inputStream.read(buffer)) != -1) { + out.write(buffer, 0, n); + } + + return out.toString(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } +}