21xrx.com
2024-09-17 03:59:32 Tuesday
登录
文章检索 我的文章 写文章
Java开发周记:分享优秀的IO工具类
2023-06-15 17:52:15 深夜i     --     --
Java IO 工具类

最近在开发项目过程中,遇到了需要读取大量的文本文件并进行分析处理的问题。为了避免重复造轮子并提高开发效率,我找到了一份优秀的Java IO工具类来帮助我完成任务。这份工具类的代码十分简洁明了,易于使用,效率也十分出色。

以下是这份IO工具类的核心代码:


public static String readFileAsString(String filePath) throws IOException {

  byte[] buffer = new byte[(int) new File(filePath).length()];

  BufferedInputStream f = null;

  try {

    f = new BufferedInputStream(new FileInputStream(filePath));

    f.read(buffer);

  } finally {

    if (f != null) try { f.close(); } catch (IOException ignored) { }

  }

  return new String(buffer);

}

public static List readLines(String filePath, Charset charset) throws IOException {

  try (Stream lines = Files.lines(Paths.get(filePath), charset)) {

    return lines.collect(Collectors.toList());

  }

}

public static void writeToFile(String content, String filePath) throws IOException {

  try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath), Charset.forName("UTF-8"))) {

    writer.write(content);

  }

}

使用这份工具类,我们可以轻松地完成诸如读取文件内容、按行读取文件以及将内容写入到文件等常用的IO操作。

感谢这份工具类的作者,让我的开发工作事半功倍,希望能够和大家分享。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复