【问题标题】:How to load a text file to a string variable in java如何将文本文件加载到java中的字符串变量
【发布时间】:2020-12-06 09:35:26
【问题描述】:

我是编程界的新手,我找不到关于如何使用 eclpise 将 txt 文件加载到 java 中的字符串变量的很好解释。

到目前为止,据我所知,我应该使用 StdIn 类,并且我知道 txt 文件需要位于我的 eclipse 工作区中(源文件夹之外),但我不知道知道我需要在代码中写什么才能将给定的文件加载到变量中。

我真的需要一些帮助。

【问题讨论】:

    标签: java eclipse text-files java.util.scanner stdin


    【解决方案1】:

    虽然我不是 Java 专家,但我很确定 this is the information you're looking for 看起来像这样:

    static String readFile(String path, Charset encoding)
      throws IOException
    {
      byte[] encoded = Files.readAllBytes(Paths.get(path));
      return new String(encoded, encoding);
    }
    

    基本上所有语言都为您提供了一些从您所在的文件系统中读取的方法。希望对您有用!

    祝你的项目好运!

    【讨论】:

    • 要放入String,OP应该使用String[] Files.readAllLines(Paths.get(path))。
    • Files.readString 将在一次调用中完成所有这些工作(在 Java 11 中添加)。
    【解决方案2】:

    要读取文件并将其存储在String 中,您可以使用String 或StringBuilder:

    1. 您需要使用FileReader 的构造函数定义BufferedReader 以传递文件名并使其准备好从文件中读取。
    2. 使用StringBuilder 将每一行结果附加到它。
    3. 读取完成后,将结果添加到String 数据中。
    public static void main(String[] args) {
        String data = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader("filename"));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
    
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            data = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多