I am loading text file contents to GUI using this code:
try {
BufferedReader br = new BufferedReader(new FileReader ("text.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("TITLE")) {
jTextField2.setText(line.substring(11, 59));
}
}
in.close();
} catch (Exception e) {
}
Then contents of text.txt file:
JOURNAL journal name A12340001
TITLE Sound, mobility and landscapes of exhibition: radio-guided A12340002
tours at the Science Museum A12340003
AUTHOR authors name A12340004
On jTextField2
I am getting this line: "Sound, mobility and landscapes of exhibition: radio-guided".
The problem is I don't know how to get to jTextField2
the string of next line "tours at the Science Museum".
I would like to ask how can I get both line on jTextField2
i.e. "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum"?
Thank you in advance for any help.
If you are using Java 8 and assuming that the columns have a fixed number of characters, you could something like this:
The first column is the key. When the keys does not exist, the last key is used. A
Map
is used to store the keys and the values. When the key already exist, the value is merged with the existing one by concatenation.This code outputs the expected String:
Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum
.EDIT: For Java 7
An empty (all spaces) first column indicates that a line is the continuation of the previous one. So you can buffer the lines and repeatedly concatenate them, until you get a non-empty first column, and then write/print the whole line.
you can do this First of all read the entire file into a string object. then get the indexes of the TITLE and AUTHOR like
int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR");
then add the length of TITLE into start indexstart+="TITLE".length();
and subtract the length of AUTHOR from end indexend-="AUTHOR".length();
at last you have the start and end index of text that you want. so get the text like.Why not create a
MyFile
class that does the parsing for you, storing key-value-pairs in aMap<String, String>
, which you can then access. This will make your code more readable and will be easier to maintain.Something like the following:
This will parse the entire file first. The expected format of the file is:
This allows for variable length keys.
Allowing you to handle exceptions separately, and then easily reference the contents of the file like so: