Java程序读取文本文件并删除重复的字符串并写入新的文本文件 [英] Java program to read text file and remove duplicate string and write new text file
本文介绍了Java程序读取文本文件并删除重复的字符串并写入新的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入文件--- hello.txt文件
你好
java
你好
java
输出文件 - xyz.txt文件
你好
java
我尝试过:
input file---hello.txt file
hello
java
hello
java
output file--xyz.txt file
hello
java
What I have tried:
public static void main(String[] args) throws IOException
{
// PrintWriter object for output.txt
PrintWriter pw = new PrintWriter("output.txt");
// BufferedReader object for input.txt
BufferedReader br1 = new BufferedReader(new FileReader("input.txt"));
String line1 = br1.readLine();
// loop for each line of input.txt
while(line1 != null)
{
boolean flag = false;
// BufferedReader object for output.txt
BufferedReader br2 = new BufferedReader(new FileReader("output.txt"));
String line2 = br2.readLine();
// loop for each line of output.txt
while(line2 != null)
{
if(line1.equals(line2))
{
flag = true;
break;
}
line2 = br2.readLine();
}
// if flag = false
// write line of input.txt to output.txt
if(!flag){
pw.println(line1);
// flushing is important here
pw.flush();
}
line1 = br1.readLine();
}
// closing resources
br1.close();
pw.close();
System.out.println("File operation performed successfully");
}
}
推荐答案
如果不需要双循环,Java有删除重复项的方法...
Java has means of removing duplicates, if double-loop isn't a requirement...
String[] szInput = {"input file---hello.txt file", "hello", "java", "hello", "java", "output file--xyz.txt file", "hello", "java"}; // you create it by reading all lines of the input file!!!
Set<String> szSet = new HashSet<String>(Arrays.asList(szInput)); // the same string will create the same hash so duplicates will be removed...
String[] szOutput = szSet.toArray(new String[szSet.size()]); // write to output file
这篇关于Java程序读取文本文件并删除重复的字符串并写入新的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文