【问题标题】:How to set String equal to text in .txt file [duplicate]如何设置字符串等于.txt文件中的文本[重复]
【发布时间】:2012-11-30 20:45:43
【问题描述】:

可能重复:
How to create a Java String from the contents of a file

我有一个要保存在字符串变量中的 .txt 文件。我用File f = new File("test.txt"); 导入了文件。现在我试图把它的内容放在一个String 变量中。我找不到关于如何做到这一点的明确解释。

【问题讨论】:

  • 欢迎来到本站。当你准备你的问题时,请注意可能的重复框。事实证明,这是一个很常见的请求。
  • 你看过我对你其他问题的回答吗?如果没有,请在此处查看:stackoverflow.com/a/13852139/540552

标签: java string variables text


【解决方案1】:

使用Scanner:

Scanner file = new Scanner(new File("test.txt"));

String contents = file.nextLine();

file.close();

当然,如果您的文件有多行,您可以多次调用nextLine。

【讨论】:

    【解决方案2】:
    BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
    
        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        String everything = sb.toString();
    } finally {
        br.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 2020-11-09
      • 2014-02-13
      • 2015-05-09
      • 1970-01-01
      相关资源
      最近更新 更多