下面是我读取txt文件的代码,但我似乎无法正确地安排文件内容的输出。
这是文件内容:
雄鹿taguig 13 pito dingal 26男pateros 多尼·马丁内斯,24岁,男性,哈哥诺伊
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] + " ");
}
}
}
}输出:
文蒂·拉多13名男性taguig pito dingal 26名男性pateros dony martinez 24名男性hagonoy
期望产出:
雄鹿taguig 13 pito dingal 26男pateros 多尼·马丁内斯,24岁,男性,哈哥诺伊
发布于 2015-04-21 16:09:44
将状态更改为
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();发布于 2015-04-21 16:13:08
不需要换行的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);
}
}https://stackoverflow.com/questions/29777600
复制相似问题