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

Reading txt files and display the data with a line break

这是我读取 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();

您不需要 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;
            }
        }
    }
}

如果您只是打印出文件中的内容,我不明白您为什么必须执行拆分。您在单个 space 上拆分,然后在每个值之间用 space 打印回值。只需打印从文件中读取的行。

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);
    }
}