gpt4 book ai didi

java - 读取txt文件并用换行符显示数据

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

这是我读取 txt 文件的代码,但我似乎无法正确安排文件内容的输出。

这是文件内容:

venti lador 13 male taguig

pito dingal 26 male pateros

dony martinez 24 male hagonoy

package testprojects;

import java.io.BufferedReader;
import java.io.FileReader;

public class ReadTextFile {
public static void main(String args[]) throws Exception {
BufferedReader bf = new BufferedReader(new FileReader("C://Users/PAO/Desktop/sampletxt.txt"));
String line;

while ((line = bf.readLine()) != null) {
String[] value = line.split(" ");

for (int x = 0; x < value.length; x++) {
if (x >= 5) {
System.out.println();
}
System.out.print(value[x] + " ");
}
}
}
}

输出:

venti lador 13 male taguig pito dingal 26 male pateros dony martinez 24 male hagonoy

期望的输出:

venti lador 13 male taguig

pito dingal 26 male pateros

dony martinez 24 male hagonoy

最佳答案

将您的条件更改为

if((x + 1) % 5 == 0 || (x == value.length - 1))

这样它就会在每 5 个数据处跳行,或者如果您到达行的最后一个数据。

你会得到这样的东西:

System.out.print(value[x] + " " );
if((x + 1) % 5 == 0 || (x == value.length - 1))
System.out.println();

关于java - 读取txt文件并用换行符显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29777600/

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