-1

I've been researching on the web how to go about this and what class is best to use for file parsing ect.

I've been programming In java for awhile now and parsing files and writing to them has always been one of weakest points literally I just don't understand It.

Specifically I have a file named

jihoon.txt

its contents are this

username = ji
password = kim106
id = 0

i want to store ji into a string variable, and kim106 into a string variable and id into an int variable while disregarding "username = " ect. Could someone please help thanks in advance :).

Hoon
  • 395
  • 1
  • 4
  • 8
  • Can you guarantee that the file will always have these items and in this order? If not then really I would be considering saving them as name value pairs. – ThePerson Mar 01 '13 at 20:30
  • 1
    Take a look at one of the many configuration file libraries out there. Apache Commons Java Configuration -> http://commons.apache.org/proper/commons-configuration/ is a fine piece. –  Mar 01 '13 at 20:31

3 Answers3

1

A good way would be to use the file as a Property. This way you can load everything the way you want.

You would load you file as such :

properties.load(new FileInputStream("path/jihoon.txt"));

Then you can access your data as such :

String value = properties.getProperty(key);

Knowing what the key is for your values you can have something like this (according to your example in the question) :

int id = Integer.parseInt(properties.getProperty("id")).intValue();
String username = properties.getProperty("username");
String password = properties.getProperty("password");

Then this way you don't have to worry about the order of your file.

See also

Community
  • 1
  • 1
blo0p3r
  • 6,790
  • 8
  • 49
  • 68
0

Why variables? How about a HashMap?

HashMap<String, String> keyValueMap = new HashMap<>();

and then feed the pairs after splitting at = there.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
-1

A properties file would be best for these kinds of operations

Example

Justin Jasmann
  • 2,363
  • 2
  • 14
  • 18