这是我读取txt文件的代码,但我似乎无法正确安排文件内容的输出。
这是文件内容:
venti lador 13 male taguig
pito dingal 26男性pateros
dony martinez 24男性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男性taguig pito dingal 26男性pateros dony martinez 24雄性hagonoy
期望的输出:
venti lador 13 male taguig
pito dingal 26男性pateros
dony martinez 24男性hagonoy
答案 0 :(得分:3)
将您的条件更改为
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();
答案 1 :(得分:1)
你不需要断言的if语句,只需将你的println()放在for循环之后。
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 (String value1 : value) {
System.out.print(value1 + " ");
}
System.out.println(""); // Goes to the next line after printing all values
}
}
如果您想要每行一定数量的值(例如5个),请尝试以下操作:
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new FileReader("C://Users/PAO/Desktop/sampletxt.txt"));
String line;
int count = 0;
while((line=bf.readLine())!=null){
String[] value=line.split(" ");
for (String value1 : value) {
System.out.print(value1 + " ");
count++;
if (count == 5) { // Five values per line before a line break
System.out.println("");
count = 0;
}
}
}
}
如果您只是打印出文件中的内容,我不明白为什么必须执行拆分。您正在拆分单个空间,然后将值打印出来,每个值之间都有一个空格。只需打印从文件中读取的行。
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){
System.out.println(line);
}
}