I solve this by making my own library based on class annotations. It’s very simple to do!
The idea is 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 that:
@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 annotation @Layout there is only illustrative, to demonstrate that the parser could read different separators besides tab (such as comma and semicolon), if you needed.
You may also have note specializations @Layoutfield to read numbers or formatted dates, and enter the format in specific properties of these other annotations.
In case, you’d have something like:
- @Datelayoutfield(position = 5, format = dd/MM/yyyy)
- @Numerlayoutfield(position = 6, format = #0.00).
In case of need, you can reuse almost all the code to make the reverse operation using the same layout statement, ie you can use the same layout statement both to read the from text file to objects how much to read from objects to text file.
In short, to implement this you will need only:
- How 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 lines of the files represented in data structures, it’s very easy to do whatever you want with this in Java, for example map to database via JPA, serialize to send over the network, etc.
Of course I’m considering that you have to read more than one layout, and eventually you’re always adding the readability of new layouts to the project. If you only have one type of text file to read, then it’s not worth it.
There is a pattern of separation between items?
– user28595
@Diegof each column is separated by t(tab);
– Bruno Tinelli
And lines for normal line breaks( n)?
– user28595
@Diegof yes, are separated by n.
– Bruno Tinelli