gpt4 book ai didi

java - 打印文本文件的字符串

转载 作者:行者123 更新时间:2023-11-30 07:31:33 25 4
gpt4 key购买 nike

在这种情况下我将如何打印元素,即文件中的单词。我的程序当前从一个名为 input 的文件中获取输入,其中包含单词“一二三四加仑”,就像这样。截至目前,它将每个单词列出在单独的行上,一旦到达“galumph”,它就会终止,这就是我想要的,但我也希望它在任何内容之前显示文件中的所有元素。我该怎么做呢?我一开始就尝试做一个 while 循环,但出现错误。有什么建议吗?

import java.io.*;
import java.util.Scanner;
class EchoWords {

public static void main(String[] args) throws FileNotFoundException {
String word;
String line;
try {
File file = new File("input");
Scanner s2 = new Scanner(file);

while(s2.hasNext()) {
String s = s2.next();
System.out.println(s);

while(true) {
word = s2.next();
if(word.equals("galumph")) {
break;
}else{
System.out.println(word);
continue;
}
}
System.out.println("bye!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

最佳答案

如果您的文件不太大,您可以一次读取文件的所有行并将它们存储在列表中:

String fileName = "filePath";
List<String> allLines = Files.readAllLines( Paths.get( fileName ) );

然后您可以随意遍历各行:

//print all the lines
for ( String line : allLines )
{
System.out.println( line );
}

//print until galumph
for ( String line : allLines )
{
if ( "galumph".equals( line ) )
{
break;
}
else
{
System.out.println( line );
}

}

此方法的优点是您只需读取文件一次。

关于java - 打印文本文件的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36046473/

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