Java:从文件中读取由井号(#)

时间:2018-11-24 15:18:57

标签: java

我想问一下从文件上在java上打印文本,但是用井号(#)隔开。

这是文本文件示例:

Chicken#2#Theone#1993#NoneRooster#3#Bone, the roost#1992#None

我想要的格式是:

Chicken    |    2    |    Theone             |    1993    |    None
Rooster    |    3    |    Bone, The Roost    |    1992    |    None

我真的不知道ArrayList和文件处理如何在Java中工作,如果你们能提供一种详细的方法,那将是很可爱的。

预先感谢

2 个答案:

答案 0 :(得分:0)

假设您的输入是(带有行)

Chicken#2#Theone#1993#None
Rooster#3#Bone, the roost#1992#None

然后您可以尝试

String input = "Chicken#2#Theone#1993#None\n" +
            "Rooster#3#Bone, the roost#1992#None";
    try(BufferedReader br = new BufferedReader(new StringReader(input))){
        String line;
        while((line = br.readLine()) != null) {
            String[] cols = line.split("#");
            System.out.print(cols[0]);
            for (int i = 1; i < cols.length; i++) {
                System.out.print("|" + cols[i]);
            }
            System.out.println();
        }
    }

答案 1 :(得分:0)

假设您的文件是Text.txt,并且其中包含这样的文本,

Chicken#2#Theone#1993#None
Rooster#3#Bone, the roost#1992#None

您可以轻松地做到这一点

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        File file = new File("Test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line;
        while ((line = br.readLine()) != null) {
            String[] words = line.split("#");
            for (int i = 0; i < words.length; i++) {
                if (i == words.length - 1) {
                    System.out.print(formatString(words[i], 20));
                } else {
                    System.out.print(formatString(words[i], 20) + "|");
                }
            }
            System.out.println();
        }

    }

    static String formatString(String word, int length) {
        return new String(new char[5]).replace('\0', ' ') + word + new String(new char[length - word.length()]).replace('\0', ' ');
    }
}