Mapping objects from files in Java

I want to map my objects from a text file. The content of the text file is as follows:

~
attribute1value
attribute2value
attribute3value
attribute4value
attribute5value
attribute6value
~
attribute1value
attribute2value
attribute3value
attribute4value
attribute5value
attribute6value
...continued same

Therefore, for each five attributes, I want to create a new object and map these six attributes to it (this is not a problem). The problem is how I read the time zone bar, how to get the first group, the second group, etc thank you

Solution

This is a more flexible approach We can specify a custom (single line) separator, which is actually not required at the beginning or end of the file (but can be given), and the number of lines of records is flexible The data is parsed into a simple model that can be used to validate the data and create the final object

private String recordDelimiter = "~";

public static List<List<String>> parse(Reader reader) {

   List<List<String>> result = new ArrayList<List<String>>();
   List<String> record = new ArrayList<String>();
   boolean isFirstLine = true;

   while ((line = reader.readLine()) != null) {

      line = line.trim();

      if (line.length() == 0) {
        continue;  // we skip empty lines
      }

      if (delimiter.equals(line.trim()) {
        if (!isFirstLine) {
          result.add(record);
          record = new ArrayList<String>();
        } else {
          isFirstLine = false;   // we ignore a delimiter in the first line.
        }
        continue;
      } 

      record.add(line);
      isFirstLine = false;
   }

   if (!result.contains(record))
     result.add(record);   // in case the last line is not a separator

   return result;

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>