簡體   English   中英

從文件讀取輸入直到讀取特定單詞

[英]reading input from file until specific word is read

我正在編寫一個 java 程序來讀取一個文件並將輸出打印到另一個字符串變量。它按預期使用代碼完美運行。

{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();

while (line != null) {
    key += line;
    line = reader.readLine();
}

System.out.println(key); //this prints contents of .txt file
}

這會在文件中打印整個文本。但我只想打印行,直到在文件中遇到單詞 END。

示例:如果 input.txt 文件包含以下文本:此測試文件 END extra in

它應該只打印:這個測試文件

只需做一個簡單的 indexOf 即可查看它在哪里以及它是否存在於該行中。 如果找到該實例,則一種選擇是使用 substring 切斷所有內容,直到關鍵字的索引為止。 盡管嘗試使用 java 正則表達式,但要獲得更多控制。

String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();

while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
    key += line;


System.out.println(key);

我不知道為什么它需要比這更復雜:

BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String str = re.readLine();
        if (str.equals("exit")) break;

     // whatever other code.

    }

您必須更改邏輯以檢查該行是否包含“END”。

如果在一行中找不到 END,則將該行添加到程序中的 key string

如果是,將該行拆分為單詞數組,閱讀該行直到遇到單詞“END”並將其附加到您的密鑰字符串。 考慮使用 Stringbuilder 作為鍵。

   while (line != null) {

        line = reader.readLine();
        if(!line.contains("END")){
            key += line;
        }else{

            //Note that you can use split logic like below, or use java substring
            String[] words = line.split("");
            for(String s : words){
                if(s.equals("END")){
                    return key;
                }
                key += s;
            }
        }
    }

您可以通過多種方式做到這一點。 其中之一是使用indexOf方法指定輸入中“END”的起始索引,然后使用subString方法。

有關更多信息,請閱讀String calss 的文檔。 在這里

這將適用於您的問題。

    public static void main(String[] args) throws IOException {
    String key = "";

    FileReader file = new FileReader("/home/halil/khalil.txt");

    BufferedReader reader = new BufferedReader(file);
    String line = reader.readLine();

    while (line != null) {
        key += line;
        line = reader.readLine();
    } String output = "";
    if(key.contains("END")) {
        output = key.split("END")[0];
        System.out.println(output);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM