gpt4 book ai didi

java - java中读取文本文件

转载 作者:行者123 更新时间:2023-12-02 08:02:10 24 4
gpt4 key购买 nike

这里我试图读取一个仅包含整数的文本文件。在每一行中。例如:

1 
2

3
1

我编写了以下代码来读取文本文件。代码如下所示。

 package fileread;
import java.io.*;

public class Main {


public static void main(String[] args) {
// TODO code application logic here
try{
FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
}

}

现在我只想检索那些重复的整数并将其显示给用户。在本例中我想显示“1”。

如何用 Java 实现这个?

最佳答案

package fileread;
import java.io.*;
import java.util.HashSet;
import java.util.Set;

public class Main {


public static void main(String[] args) {
Set<String> uniqueLines = new HashSet<String>();
Set<String> duplicatedLines = new HashSet<String>();
try{
FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (uniqueLines.contains(str)) {
if (!duplicatedLines.contains(str)) {
duplicatedLines.add(str);
System.out.println(str);
}
} else {
uniqueLines.add(str);
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
}

}

注意:确保您的输入每行都没有尾随空格。另请注意,当列表变长时,此实现对内存不是特别友好。

关于java - java中读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8744148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com