简体   繁体   English

Java Swing仅将文件中的唯一行读入JtextArea

[英]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 . 您好,我正在开发一个swing应用程序,该应用程序将从文本文件中读取内容并将其添加到JTextArea I am able to read the file contents using the textarea.read() method 我可以使用textarea.read()方法读取文件内容

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. 我见过有人建议使用LinkedHashSet ,但是我不知道如何在这种情况下使用它。

I need a solution that can read only unique lines from the text file and put it into the jTextArea . 我需要一个只能从文本文件读取唯一行并将其放入jTextArea的解决方案。

I need a solution that can read only unique lines from the text file and put it into the jTextArea. 我需要一个只能从文本文件读取唯一行并将其放入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. 您可以创建一个while循环,以读取输入文件的每一行,将此行分配给String变量,并将此行添加到此循环外部声明的LinkedHashSet<String> yourSet You can add these lines (Strings) to yourSet with the method yourSet.add(String yourString) . 您可以使用yourSet.add(String yourString)方法将这些行(字符串)添加到yourSet After that you could iterate over your set and send each String line to yourJTextArea : 之后,您可以遍历集合并将每个String行发送到yourJTextArea

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

You should read the file line by line using .readLine() and add the line to a HashSet Object, sets only allow unique elements. 您应该使用.readLine()逐行读取文件,并将该行添加到HashSet对象中,设置仅允许唯一元素。 Once you have read the entire file and added them to the set you can just add the String to the textarea 阅读完整个文件并将其添加到集合中后,您只需将String添加到textarea

Set is really good solution. 设置确实是很好的解决方案。 In this context read file from new line in.nextLine() store value in String str = new String(value) and then set.add(str) After fill you textArea with values from Set 在这种情况下,从in.nextLine()的新行中读取文件。将值存储在String str = new String(value)中,然后进行set.add(str)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM