Reputation: 3
I'm trying to write a small Java application, and part of its job is to read, write, and parse lines from text files. My problem though is taking a line from a text file, reading it, and breaking it into parts. For example, an example line is:
Tuesday, 11/11/14 10:30:32: 3.93
I want my program to be able to look at this and fill up for example a string day = "tuesday"
, and value = 3.93
.
FileReader fileReader = new FileReader(itemValue);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + "\n");
int[] value;
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
This is the code I currently have - it will parse through my file and print out line by line into the console, but I don't really know how to actually process the line. I've tried using bufferedReader.readLine as the variable containing the line, but that doesn't seem to be the answer. I'm extremely new to Java and this is a big roadblock in my programming, so if anybody could point me toward a solution, that would be awesome. Thanks in advance! :)
Edit: All of my data looks exactly the same, here is the rest of it.
Tuesday, 11/11/14 10:29:23: 4.48
Tuesday, 11/11/14 10:29:27: 5.0
Tuesday, 11/11/14 10:29:39: 5.95
Tuesday, 11/11/14 10:29:46: 6.0
Tuesday, 11/11/14 18:07:25: 4.0
Tuesday, 11/11/14 18:07:27: 4.5
Tuesday, 11/11/14 18:07:33: 5.0
Tuesday, 11/11/14 18:07:39: 5.9
Tuesday, 11/11/14 18:07:51: 20.0
Upvotes: 0
Views: 2306
Reputation: 11832
Two of the most popular approaches to parsing this kind of data are String.split()
, and using a regular expression.
With String.split()
you might do something like this:
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\\s+");
// now each part of the input line (separated by whitespace) is in a different element of the parts array
}
If you choose to use a regular expression, and you wanted the first and last parts, you might try a regular expression like:
^(A-Za-z), .*? (0-9\.)$
Of course there will be other code required to execute it. Do a google search for "regular expressions".
Upvotes: 1
Reputation: 6258
You could try to break up each line by white space using a delimiter.
String line;
while ((line = bufferedReader.readLine()) != null) {
String values[] = line.split("\\s+");
}
This gives you some starting point to work with each bit of data in the line. As Jason pointed out in the comments, it can vary widely, depending on the implementation.
In this case, for example, you could parse the last item in each values[]
to a double. It's up to you.
Upvotes: 2