How to create objects from a text file in Java?

Asked

Viewed 1,168 times

0

Hello. I have a class in my project (Person) that contains attributes (e.g., name, age, gender, etc.) and I have an array of these objects (Person). I also have a text file and inside it is typed several features in a format Name#Age#Sex, for example Ana#20#Female in one line, Paulo#31#Male in the next. I would like to know if there is the possibility when the program reads this txt file, identify that there is a String before the # character and save it in a variable. Thus, I could create an object with the characteristics of the file provided (type like this: Person p = new Person ("Ana","20","Feminine"). With this, I identify the attributes, create objects and place inside my array.

  • 2

    See how to read text file: http://www.devmedia.com.br/lendo-dados-de-txt-com-java/23221. Then, for each line, use the method linha.split("#") to obtain an array with the value of each attribute. When you already have some code, if it’s not working well, feel free to update the question and count on our help.

  • @Caffé, wouldn’t it be better to make an answer with your comment? because I believe that is the answer to the question.

  • I did so and it worked: String result [ ] = line.split("#"); .

1 answer

0


See how to read text file in Java:

Reading data from Txt with Java

Then, for each line, use the method linha.split("#") to obtain an array with the value of each attribute:

String atributosPessoa [ ] = line.split(“#”);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.