gpt4 book ai didi

java - 从文本文件中获取每第 n 行,反转并打印出来

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

我编写的函数获取:文件路径和数字作为参数。函数打开此文件并从中获取每第 n 行,反转它并打印到控制台。

到目前为止,我设法做类似的事情:

public static void reverseText(String filePath, int colle) // int colle = n-th line
{
BufferedReader fileRead = null;

String line;

try
{
File file = new File(filePath);
if (!(file.exists()))
file.createNewFile();

fileRead = new BufferedReader(new FileReader(file));

while ((line = fileRead.readLine()) != null)
{

}


fileRead.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}

我的意思是,例如在文件中包含以下文本行(int colle = 2,因此我们得到文件的每第二行)

第一行
第二行
<-- 这个
第三行
第四行
<--还有这个

(读取文件并反向获取行)-->在控制台中打印输出:

“埃尼尔·诺塞斯”“埃尼尔·赫特鲁夫”

我想对于反向我应该使用 StringBuilder 但首先我需要获取这些行,但我不知道如何读取每个第 n 行...

感谢您的帮助!

最佳答案

下面的解决方案读取所有行,然后选择每个 n 行,反转并打印。

public static void main(String[] args) throws IOException {
int frequency = 5;
final List<String> strings = Files.readAllLines(Paths.get("/home/test.txt"));
List<String> collect = IntStream.range(0, strings.size())
.filter(c -> c % frequency == 0)
.mapToObj(c -> strings.get(c))
.collect(Collectors.toList());

collect.forEach(str ->
System.out.println(new StringBuilder(str).reverse())
);
}

IntStream 是从集合字符串中获取特定行所必需的。然后一行一行地反转并打印。它可以是一行,但决定使其更具可读性。

关于java - 从文本文件中获取每第 n 行,反转并打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724527/

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