gpt4 book ai didi

java - 带有数组列表的 I/O

转载 作者:行者123 更新时间:2023-12-02 02:52:52 24 4
gpt4 key购买 nike

我只是想知道是否有一种方法可以循环遍历文本文件,直到找到特定的字符串。例如,假设您有一个文本文件,其中包含以下内容:

香蕉

苹果

葡萄

甜瓜

橙色

樱桃

草莓巧克力 Vanilla

我基本上想编写一个程序,循环遍历输入文件,直到到达用户指定的特定字符串,然后将下一行存储在数组列表中。所以,基本上说,如果我估算樱桃,我希望它将草莓、巧克力、 Vanilla 存储在数组列表中。对于我的一生,我无法弄清楚如何做到这一点,所以任何事情都会受到赞赏。到目前为止我所拥有的如下。

public static void main(String[] args) throws IOException {
String line;
ArrayList<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);

BufferedReader reader = new BufferedReader(file);

System.out.print("What fruit do you want: ");
String fruit = in.next();
line = reader.readLine();


while ((line != null)) {
if(line.equals(fruit){
}
}

最佳答案

只需循环输入,直到遇到搜索到的行,然后将找到的每一行存储在列表中。

    String line;

while((line = reader.readLine()) != null)
if(line.equals(fruit))
break;

ArrayList<String> lines = new ArrayList<>();
while((line = reader.readLine()) != null)
lines.add(line);

关于java - 带有数组列表的 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43543397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com