【问题标题】:Read from txt file - Save when a line-break occurs从 txt 文件中读取 - 发生换行时保存
【发布时间】:2016-06-15 20:18:02
【问题描述】:

我想从 .txt 文件中读取,但我想在出现空行时保存每个字符串,例如:

All
Of
This
Is
One
String

But
Here
Is A
Second One

AllString 的每个单词都将保存为一个字符串,而从But 和转发的每个单词都将保存为另一个。这是我当前的代码:

public static String getFile(String namn) {
    String userHomeFolder = System.getProperty("user.home");
    String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
    int counter = 0;
    Scanner inFil = new Scanner(new File(filnamn));
    while (inFil.hasNext()) {
        String fråga = inFil.next();
        question.add(fråga);
    }
    inFil.close();

}

我应该如何调整它?目前,它将每一行保存为一个字符串。提前致谢。

【问题讨论】:

  • 这是一个很好的问题,如果您为您使用的语言添加标签,它将获得更多浏览量。

标签: java string line


【解决方案1】:

我假设您的问题是关于 java.
如您所见,我将您的方法的返回类型更改为 List,因为在将全文拆分为多个字符串时返回单个字符串没有意义。
我也不知道question 是什么变量,所以我将它切换为allParts,它是由空行分隔的句子列表(变量part)。

public static List<String> getFile(String namn) throws FileNotFoundException {
    String userHomeFolder = System.getProperty("user.home");
    String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt";
    int counter = 0;

    // this list will keep all sentence
    List<String> allParts = new ArrayList<String>(); s

    Scanner inFil = new Scanner(new File(filnamn));

    // part keeps single sentence temporarily
    String part = "";
    while (inFil.hasNextLine()) { 
        String fråga = inFil.nextLine(); //reads next line
        if(!fråga.equals("")) {       // if line is not empty then
                part += " " + fråga;      // add it to current sentence
            } else {                  // else     
                allParts.add(part);       // save current sentence
                part = "";                // clear temporary sentence
            }

        }
        inFil.close();
        return allParts;

    }

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多