如何从Java中的文本文件读取格式化的数据

时间:2018-10-11 08:50:50

标签: java arrays file java.util.scanner

因此,在过去的一周中,我已经完成了这项任务,而在这项任务中我要做的一件事情是从文本文件中读取格式化的数据。格式化的意思是这样的:

{
    Marsha      1234     Florida   1268
    Jane        1523     Texas     4456
    Mark        7253     Georgia   1234
}

(注意:这只是一个例子。不是我分配的实际数据。)

现在我一直在尝试自己解决这个问题。我尝试将每一行读取为一个字符串,并使用.substring()获取该字符串的某些部分并将其放入数组中,然后从数组中获取该字符串的索引并将其打印到屏幕上。现在,我尝试了这种想法的几种不同变体,但它没有用。它要么以错误结尾,要么以奇怪的方式输出数据。现在的任务是明天到期,我不知道该怎么办。如果有人可以在这个问题上为我提供一些帮助,将不胜感激。

4 个答案:

答案 0 :(得分:1)

对于您给出的示例,使用正则表达式模式\s+分割行将起作用:

String s = "Marsha      1234     Florida   1268";
s.split("\\s+");

得到一个包含4个元素“ Marsha”,“ 1234”,“ Florida”和“ 1268”的数组。

我使用的模式匹配一​​个或多个空格字符-有关详细信息和其他选项,请参见The JavaDocs of Pattern


另一种方法是定义您的生产线需要整体匹配的模式,并捕获您感兴趣的组:

String s = "Marsha      1234     Florida   1268";

Pattern pattern = Pattern.compile("(\\w+)\\s+(\\d+)\\s+(\\w+)\\s+(\\d+)");
Matcher matcher = pattern.matcher(s);

if (!matcher.matches())
    throw new IllegalArgumentException("line does not match the expected pattern"); //or do whatever else is appropriate for your use case

String name = matcher.group(1);
String id = matcher.group(2);
String state = matcher.group(3);
String whatever = matcher.group(4);

此模式要求第二和第四组仅由数字组成。

但是请注意,如果您的数据也可以包含空格,则这两种方法都会失效-在这种情况下,您需要使用不同的模式。

答案 1 :(得分:1)

首先,您必须知道文件的格式。就像您的示例一样,它以{开头,以}结尾。什么是数据分隔符?例如,分隔符可以是分号,空格等。知道这一点,您就可以开始构建应用程序了。在您的示例中,我将编写如下内容:

public class MainClass
{

public static void main(String[] args)
{
    String s = "{\r\n"+
               "Marsha      1234     Florida   1268\r\n" + 
               "Jane        1523     Texas     4456\r\n" + 
               "Mark        7253     Georgia   1234\r\n"+
               "}\r\n";

    String[] rows = s.split("\r\n");

    //Here we will keep evertihing without the first and the last row
    List<String> importantRows = new ArrayList<>(rows.length-2);
    //lets assume that we do not need the first and the last row
    for(int i=0; i<rows.length; i++)
    {
        //String r = rows[i];
        //System.out.println(r);

        if(i>0 && i<rows.length)
        {
            importantRows.add(rows[i]);
        }

    }

    List<String> importantWords = new ArrayList<>(rows.length-2);
    //Now lets split every 'word' from row
    for(String rowImportantData : importantRows)
    {
        String[] oneRowData = rowImportantData.split(" ");

        //Here we will have one row like: [Marsha][ ][ ][ ][1234][ ][ ][ ][Florida][ ][ ][1268]
        // We need to remove the whitespace. This happen because there is more        
        //then one whitespace one after another. You can use some regex or another approach 
        // but I will show you this because you can have data that you do not need and you want to remove it.
        for(String data : oneRowData)
        {
            if(!data.trim().isEmpty())
            {
                importantWords.add(data);
            }
            //System.out.println(data);
        }

    }

    //Now we have the words.
    //You must know the rules that apply for this data. Let's assume from your example that you have (Name Number) group
    //If we want to print every group (Name Number) and we have in this state list with [Name][Number][Name][Number]....
    //Then we can print it this way
    for(int i=0; i<importantWords.size()-1; i=i+2)
    {
        System.out.println(importantWords.get(i) + " " + importantWords.get(i+1));
    }

}

}

这只是一个例子。您可以通过许多不同的方式制作应用。重要的部分是您要知道要处理的信息的初始状态是什么,以及要获得的结果是什么。

祝你好运!

答案 2 :(得分:0)

您可以使用许多不同的方法来读取此格式化的文件。我建议您首先从文本中提取相关数据作为字符串列表,然后将各行分成多个字段。这是一个示例,说明如何使用您提供的数据样本执行此操作:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CustomTextReader {

    public static void main(String[] args) {
        String text =
                "Marsha      1234     Florida   1268\r\n" + 
                "Jane        1523     Texas     4456\r\n" + 
                "Mark        7253     Georgia   1234";

        //Extract the relevant data from the text as a list of arrays
        //  in which each array is a line, and each element is a field. 
        List<String[]> data = getData(text);
        //Just printing the results
        print(data);
    }

    private static List<String[]> getData(String text) {
        //1. Separate content into lines.
        return Arrays.stream(text.split("\r\n"))
                //2. Separate lines into fields.
                .map(s -> s.split("\\s{2,}"))
                .collect(Collectors.toList());
    }

    private static void print(List<String[]> data) {
        data.forEach(line -> {
            for(String field : line) {
                System.out.print(field + " | ");
            }
            System.out.println();
        });

    }
}

了解格式对数据有何影响,这一点很重要。如果您知道字段不包含空格,则可以使用" "\\s{2,}作为步骤2中拆分字符串的模式。但是,如果您认为数据可能包含带有空格的字段(例如, “北卡罗莱纳州”),最好使用另一个\\s{2,}之类的正则表达式(这就是我在上面的示例中所做的事情)。希望我能对您有所帮助!

答案 3 :(得分:0)

我真的相信@JoniVR的建议会非常有帮助,您应该考虑对每行的列使用分隔符。当前,您将无法解析复合数据,例如名字“ Mary Ann”。同样,由于您提供的样本数据已经有4行,因此您应该有一个POJO,它将代表从文件中解析出的数据。一个概念性的样子:

class MyPojo {

    private String name;
    private int postCode;
    private String state;
    private int cityId;

    public MyPojo(String name, int postCode, String state, int cityId) {
        this.name = name;
        this.postCode = postCode;
        this.state = state;
        this.cityId = cityId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPostCode() {
        return postCode;
    }

    public void setPostCode(int postCode) {
        this.postCode = postCode;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public int getCityId() {
        return cityId;
    }

    public void setCityId(int cityId) {
        this.cityId = cityId;
    }

    @Override
    public String toString() {
        return "MyPojo{" +
            "name='" + name + '\'' +
            ", postCode=" + postCode +
            ", state='" + state + '\'' +
            ", cityId=" + cityId +
            '}';
    }
}

然后您想在验证行之后满足错误,因此,最好考虑某种类型的Error类来存储这些错误(设计适当的类可以扩展Exception类?)。为此,一个非常简单的类是:

class InsertionError {
    private String message;
    private int lineNumber;

    public InsertionError(String message, int lineNumber) {
        this.message = message;
        this.lineNumber = lineNumber;
    }

    @Override
    public String toString() {
        return "Error at line " + lineNumber + " -> " + message;
    }
}

然后解决方案本身应该:
1.分割线。
2.标记每行中的列,然后解析/验证它们。
3.以有用的Java表示形式收集列数据。

也许像这样:

private static final int HEADERS_COUNT = 4;
private static final int LINE_NUMBER_CURSOR = 0;

public static void main(String[] args) {
    String data =   "Marsha      1234     Florida   1268\n" +
                    "Jasmine     Texas    4456\n" +
                    "Jane        1523     Texas     4456\n" +
                    "Jasmine     Texas    2233      asd\n" +
                    "Mark        7253     Georgia   1234";

    int[] lineNumber = new int[1];

    List<InsertionError> errors = new ArrayList<>();

    List<MyPojo> insertedPojo = Arrays.stream(data.split("\n"))
        .map(x -> x.split("\\p{Blank}+"))
        .map(x -> {
            lineNumber[LINE_NUMBER_CURSOR]++;

            if (x.length == HEADERS_COUNT) {
                Integer postCode = null;
                Integer cityId = null;

                try {
                    postCode = Integer.valueOf(x[1]);
                } catch (NumberFormatException ignored) {
                    errors.add(new InsertionError("\"" + x[1] + "\" is not a numeric value.", lineNumber[LINE_NUMBER_CURSOR]));
                }

                try {
                    cityId = Integer.valueOf(x[3]);
                } catch (NumberFormatException ignored) {
                    errors.add(new InsertionError("\"" + x[3] + "\" is not a numeric value.", lineNumber[LINE_NUMBER_CURSOR]));
                }

                if (postCode != null && cityId != null) {
                    return new MyPojo(x[0], postCode, x[2], cityId);
                }
            } else {
                errors.add(new InsertionError("Columns count does not match headers count.", lineNumber[LINE_NUMBER_CURSOR]));
            }
            return null;
        })
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

    errors.forEach(System.out::println);

    System.out.println("Number of successfully inserted Pojos is " + insertedPojo.size() + ". Respectively they are: ");

    insertedPojo.forEach(System.out::println);
}

,它打印:

  

第2行出现错误->列数与标题数不匹配。
  第4行->“ Texas”的错误不是数字值。
  第4行->“ asd”的错误不是数字值。
  成功插入的Pojos数为3。分别是:
  MyPojo {name ='Marsha',postCode = 1234,state ='Florida',cityId = 1268}
  MyPojo {name ='Jane',postCode = 1523,state ='Texas',cityId = 4456}
  MyPojo {name ='Mark',postCode = 7253,state ='Georgia',cityId = 1234}