I solve this by doing my own library based on class annotations. It's very simple to do!
The idea is to declare the different layouts of TXT files as Java classes, and then use a generic parser that, from a given layout (a Java class), interprets a text file, resulting in an instance of that same class or a list of instances.
Something like this:
@Layout(separator = LayoutSeparator.TAB)
class LayoutPessoa {
@LayoutField(position = 0)
Integer codigo;
@LayoutField(position = 1)
String nome;
@LayoutField(position = 2)
String celular;
@LayoutField(position = 3)
String telefone;
@LayoutField(position = 4)
String telefoneTrabalho
}
class Main {
public void static main(String[] args) {
LayoutParser parser = new LayoutParser(LayoutPessoa.class);
List<LayoutPessoa> pessoas = parser.parse(conteutoArquivoTxt);
for(LayoutPessoa pessoa : pessoas) {
System.out.println(pessoa.nome);
}
}
}
The @Layout annotation is just illustrative, to demonstrate that the parser could read different tabs in addition to a tab (such as a comma and a semicolon) if you needed it. >
You can also have specializations of the @LayoutField annotation to read numbers or formatted dates, and inform the format in specific properties of these other annotations.
In this case, you would have something like:
-
@DateLayoutField (position = 5, format = dd / MM / yyyy)
-
@NumerLayoutField (position = 6, format = # 0.00) .
If necessary, you can reuse almost all of the code to do the reverse operation using the same layout statement, that is, you can use the same layout statement both to read the from text file to objects and to read from objects to text file .
In short , to implement this you will need only:
- Ability to read lines from a text file;
- Know how to declare and read annotations of a class;
- Know how to instantiate classes via reflection.
Once you have the rows of the files represented in data structures, it is very easy to do whatever you want with this in Java, such as mapping to database via JPA, serializing to send over the network, etc.
Of course I'm considering that you have to read more than one layout, and eventually it's always adding the ability to read new layouts in the project. If you only have one type of text file to read, then it's not worth it.