hub hub - 6 months ago 33
Java Question

read and find string from text file

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.

Answer

Why not create a MyFile class that does the parsing for you, storing key-value-pairs in a Map<String, String>, which you can then access. This will make your code more readable and will be easier to maintain.

Something like the following:

public class MyFile {
    private Map<String, String> map;
    private String fileName;

    public MyFile(String fileName)  {
        this.map = new HashMap<>();
        this.fileName = fileName;
    }

    public void parse() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line = br.readLine();
        String title = "";
        while (line != null) {
            //Update the title only when it's not empty
            title = line.substring(0, 9).trim().equals("") ? title : line.substring(0, 9).trim();
            //If the title is contained in the map, append to the value, otherwise insert a new value
            map.put(title, map.get(title) == null ? line.substring(11, 59).trim() : map.get(title) + line.substring(11, 59).trim());
            line = br.readLine();
        }
    }

    public String getEntry(String key) {
        return map.get(key);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Entry entry:map.entrySet()) {
            sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
        }
        return sb.toString();
    }
}

This will parse the entire file first, allowing you to handle exceptions separately, and then easily reference the contents of the file like so:

MyFile journalFile = new MyFile("text.txt");
try {
    journalFile.parse();
} catch (IOException e) {
    System.err.println("Malformed file");
    e.printStackTrace();
}

jTextField2.setText(journalFile.getEntry("TITLE"));