将整个文本文件转换为 Java 中的字符串 [英] Whole text file to a String in Java

查看:31
本文介绍了将整个文本文件转换为 Java 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 是否有一行指令来读取文本文件,就像 C# 一样?

Does Java has a one line instruction to read to a text file, like what C# has?

我的意思是,Java 中是否有类似的东西?:

I mean, is there something equivalent to this in Java?:

String data = System.IO.File.ReadAllText("path to file");

如果不是……这样做的最佳方式"是什么……?

If not... what is the 'optimal way' to do this...?


我更喜欢 Java 标准库中的一种方式......我不能使用 3rd 方库..


I prefer a way within Java standard libraries... I can not use 3rd party libraries..

推荐答案

Java 11 通过 Files.readString,示例代码:

Java 11 adds support for this use-case with Files.readString, sample code:

Files.readString(Path.of("/your/directory/path/file.txt"));

在 Java 11 之前,标准库的典型方法是这样的:

Before Java 11, typical approach with standard libraries would be something like this:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}

注意事项:

  • 为了从文件中读取文本,使用 FileInputStream
  • 如果性能很重要并且您正在读取大文件,建议将流包装在 BufferedInputStream 中
  • 流应该由调用者关闭
  • in order to read text from file, use FileInputStream
  • if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
  • the stream should be closed by the caller

这篇关于将整个文本文件转换为 Java 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆