user220755
user220755

Reputation: 4446

Returning a line in a text file that contains a string

I have a text file that contains information formated in a key=value way. How do I look up the key and return the value.

For example, let's say the file has:

KeyOne=ValueOne
KeyTwo=ValueTwo

and I would like to have a method which takes KeyOne and returns ValueOne.

Upvotes: 0

Views: 135

Answers (4)

ria
ria

Reputation: 7974

In case all you need is to read name-value pairs, and if that is of configuration nature, then you can consider using properties file in Java.

You can check this out http://www.mkyong.com/java/java-properties-file-examples/

Upvotes: 1

Michael
Michael

Reputation: 2634

Whole bunch of ways. You could

a. Read the file once line by line, split the input and then populate a map

b. Apply a regex expression search to the file as a whole

c. You could index a full text search the thing

It all depends on your use case. Hard to recommend an approach without understanding the context.

Upvotes: -1

Lightyear Buzz
Lightyear Buzz

Reputation: 796

Scanner s = new Scanner("Filename");
Map<String, String> m = new HashMap<String, String>();
while(s.hasNext()){
    String line[] = s.nextLine().split("=");
    m.put(line[0], line[1]);
}

To get the value:

m.get(ValueOne);

Upvotes: 1

Geert-Jan
Geert-Jan

Reputation: 18895

Okay, I'm in a good mood :), untested:

//given that 'input' got the contents of the file

Map<String,String> m = new HashMap<String,String>();

//this can be done more efficient probably but anyway
//normalize all types of line breaks to '\n'
input = input.replaceAll("\r\n","\n");
input = input.replaceAll("\r","\n");


//populate map
String[] lines = input.split("\n");
for(int i=0 ; i< lines.length; i++){
  String[] nv = lines[i].split("=");
  m.put(nv[0],nv[1]);
}

//get value given key: 
String key = "somekey";
String someValue = m.get(key);
System.out.println(someValue);

Upvotes: 1

Related Questions