package com.walker.openocr.util; import com.walker.infrastructure.utils.FileCopyUtils; import org.springframework.core.io.ClassPathResource; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FileReaderUtils { public static final void saveJson2File(String json, String filePath){ try { FileCopyUtils.copy(json.getBytes(), new File(filePath)); } catch (IOException e) { throw new RuntimeException("json写入文件失败:" + e.getMessage(), e); } } public static final InputStream getClasspathInputStream(String fileName) throws IOException{ // ClassPathResource resource = new ClassPathResource("your-file.txt"); ClassPathResource resource = new ClassPathResource(fileName); return resource.getInputStream(); } public static List getFileLines(InputStream inputStream){ List content = new ArrayList<>(64); try (InputStreamReader read = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(read)) { String lineTxt; while ((lineTxt = bufferedReader.readLine()) != null) { // System.out.println(lineTxt); content.add(lineTxt.trim()); } } catch (Exception e) { e.printStackTrace(); System.out.println("读取文件内容出错"); } return content; } /** * 读文本内容,按行读取,返回集合。 * @param filePath 文件绝对路径 * @return */ public static List getFileLines(String filePath){ File file = new File(filePath); if(!file.exists()){ System.out.println("文件不存在,无法读取内容:" + filePath); return null; } // String encoding = "utf-8"; List content = new ArrayList<>(64); try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader bufferedReader = new BufferedReader(read)) { //判断文件是否存在 if (file.isFile() && file.exists()) { String lineTxt; while ((lineTxt = bufferedReader.readLine()) != null) { // System.out.println(lineTxt); content.add(lineTxt.trim()); } } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { e.printStackTrace(); System.out.println("读取文件内容出错"); } return content; } }