从txt文件读取 - 在发生换行时保存

时间:2016-06-15 11:48:00

标签: java string line

我想从.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();

}

我应该如何调整它?目前,它将每行保存为单个String。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我认为你的问题与java有关 正如您所看到的,我将方法的返回类型更改为List,因为在将全文拆分为多个字符串时返回单个String没有意义。
我也不知道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;

    }
相关问题