What's the best way to work with Java String that has fields mapping inside it?

I have a long line that has a specific field layout:

Char 1-6 = the type of message
Char 7 = system number
Char 8-9 = unused
Char 10 = shift number
and so on


I understand that I can just use String methods to work with this, but I hope there is something a little better that will allow me to associate fields with positions in a more meaningful way.

Does it exist? Thanks for any help.


source to share

3 answers

Have a custom class with variables, each of which defines the type of information they represent. In the constructor for this class, pass this string and initialize the values โ€‹โ€‹of the different fields by parsing the String. Then you can easily access the information that the different parts of your string represent.

You can also store the original string in an object of this new class if information about the original string is required.



I'm not really sure what you want to do, but this should work:

String typeOfMessage = str.substring(0,5);
char systemNumber  =   str.charAt(6);


... etc.



Use jsefa


... to record the length of the record ...

this way you can create a class and define positions easily

public class MyMessage {

   @FlrField(pos = 1, length = 5)
   String messageType;

   @FlrField(pos = 6, length = 1)
   String systemNumber;



Here is a quick tutorial http://jsefa.sourceforge.net/quick-tutorial.html



All Articles