【问题标题】:how to save contents of a file as single string using java如何使用java将文件的内容保存为单个字符串
【发布时间】:2020-06-18 07:47:07
【问题描述】:

我正在尝试使用分隔符从文本文件中提取特定内容。这是我的代码:

File file = new File("C:\\Inputfiles\\message.txt"); 
BufferedReader br = new BufferedReader(new FileReader(file)); 
String st; 
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}

但结果,每一行都被分隔符分割并保存为数组。

任何人都可以建议我如何将文件中的内容保存为单个字符串,因此我只能将有限数量的行保存为数组。

【问题讨论】:

  • 你能分享一个文件和你试图提取的字符串的例子吗?这会让问题更清楚
  • 我们想看看文件的几行是什么样子的......
  • 您正在拆分字符串,然后想知道为什么要拆分字符串?如果你不想要它分裂,你为什么要分裂它?

标签: java filereader


【解决方案1】:

您可以使用StringBuilderStringBuffer 来执行此操作。

    File file = new File("C:\\Inputfiles\\message.txt");
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st=br.readLine()) != null) {
        String[] strings = StringUtils.split(st, "------------");
        StringBuilder singleString = new StringBuilder();

        for(String s : strings){
            singleString.append(s);
        }
        System.out.println(singleString.toString());
    }

【讨论】:

    【解决方案2】:

    谢谢大家,

    我确实使用了以下更改

    String contents = new String(Files.readAllBytes(Paths.get("C:\\Inputfiles\\message1.txt")));
                    String[] splitted = StringUtils.split(contents, "-------");
                    for(int i=0;i<splitted.length;i++)
                        System.out.println(splitted[i]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 2018-01-16
      • 2011-08-30
      相关资源
      最近更新 更多