Search code examples
javaswingbufferedreaderfilereaderjtextarea

Java Swing read only unique lines from file into JtextArea


Hello I am developing a swing application that reads contents from the text file and adds them to the JTextArea. I am able to read the file contents using the textarea.read() method

But the problem is the text file contains many duplicates which are unnecessary and need to be discarded.

Here is the code for reading:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

BufferedReader reader = new BufferedReader(new FileReader(new File("D:/abc.txt")));          
jTextArea1.read(reader, "D:/abc.txt");

}

I've seen people suggesting the usage of LinkedHashSet, but I don't know how to use it in this context.

I need a solution that can read only unique lines from the text file and put it into the jTextArea.


Solution

  • I need a solution that can read only unique lines from the text file and put it into the jTextArea. - I think that the better solution is to read all the lines of the input file, not only those which are unique. It will be easier to do. You could create a while loop that reads each line of the input file, assign this line to the String variable and add this line to the LinkedHashSet<String> yourSet declared outside of this loop. You can add these lines (Strings) to yourSet with the method yourSet.add(String yourString). After that you could iterate over your set and send each String line to yourJTextArea:

    for(String s : yourSet) {
        yourJTextArea.append(s + "\n" );
    }