从文件读取输入直到读取特定单词

时间:2018-02-13 07:00:19

标签: java bufferedreader filereader

我正在编写一个java程序来读取文件并将输出打印到另一个字符串variable.which正在使用代码完美地工作。

{
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

它应该只打印: 这个测试文件

5 个答案:

答案 0 :(得分:0)

只需做一个简单的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);

答案 1 :(得分:0)

我不确定为什么它需要比这更复杂:

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

     // whatever other code.

    }

答案 2 :(得分:-1)

您必须更改逻辑以检查该行是否包含" END"。

如果在行中找不到END,请在程序中将该行添加到键字符串

如果是,将该行拆分为单词数组,读取该行,直到遇到单词" END"并将其附加到您的密钥字符串。考虑使用Stringbuilder作为密钥。

autoCapitalize="none"

答案 3 :(得分:-1)

你可以通过多种方式实现这一目标。其中一个是使用indexOf方法来指定" END"的起始索引。在输入中,然后使用subString方法。

有关更多信息,请阅读String calss的文档。 HERE

答案 4 :(得分:-1)

这适用于您的问题。

    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);
    }
}