Link to home
Start Free TrialLog in
Avatar of Testsubbu
Testsubbu

asked on

Read line from files based on a pattern

Dear java experts
I have a file test.file. This consists of 1000 or more lines

field1: field1Error: file1path,identifier1
field2: field2Error: file2path,identifier2
field3: field3Error: file3path,identifier3
field4: field4Error: file4path,identifier4

they are all similar pattern
i really wanto have 4 variables

String field
String Error
String Path
String id


and store them appropriately how do i read the file and store them as follows

field = field1
Error=field1Error
Path=file1path
id=identifier1

ALl thehelp is very much apprecaited.
thanks a lot,
Testsubbu
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Just split each line and put it into a custom class:

String[] fields = line.split("[:,]");
FieldInfo info = new FieldInfo();
info.setField1(fields[0].trim());
info.setError(fields[1].trim());

etc. for each line
Each FieldInfo object can be added to a collection in the loop
Avatar of aozarov
aozarov

Set validOptions = new HashSet();
validOptions.add("field");
validOptions.add("error");
validOptions.add("path");
validOptions.add("id");

for each line you read
String[] fields = line.split(",");
Map map = new HashMap();
for (int i = 0; i < fields.length; i++)
{
String keyValues[] = fields[i].split(":");
String key = keyValues[0].trim().toLowerCase();
if (validOptions.contains(key))
{
 write to file key and  keyValue[1] which is the value
}
}
Oops, I thought you have "," as seperator for key value and ":" for seperator for value.
It actually seems not to be the case.
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> I've already written the code for that
I saw what you wrote, and I wrote something different which assumes, wrongly, different semantics for ":" and ","
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>The idea to use a HashMap or Hashtable to fast manage and access the various FileInfo, as aozarov propose

That's not what the code posted by aozarov is actually doing. It's checking the validity of field identifiers in the file, which may not be there and i don't see why they should be. It was actually i who suggested using a collection for the purpose you mentioned:

>> Each FieldInfo object can be added to a collection in the loop


Sorry CEHJ, screwed up copying the name.
No problem ;-)
:-)