Java读取输入/输出将重复的字符串打印到文件中



嗨,我正在处理这个问题,假设一个图书馆正在处理一个包含书名的输入文件,以识别重复的书名。编写一个程序,从名为bookTitles.ip的输入文件中读取所有标题,并将其写入名为duplicateTitles.out的输出文件。完成后,输出文件应包含输入文件中重复的所有标题。请注意,重复的标题应该写一次,即使输入文件可能多次包含相同的标题。如果输入文件中没有重复的标题,则输出文件应为空。使用记事本或其他文本编辑器创建输入文件,每行一个标题。请确保您有多个副本,包括一些有三个或三个以上副本的副本。

到目前为止,我有这个,但如果我更改输入文件的顺序,它会多次打印重复项。谢谢

import java.io.*; 
public class Library
{ 
public static void main(String[] args) throws IOException
{ 
String line3="";
boolean dup = false;
// PrintWriter object for output.txt 
PrintWriter pw = new PrintWriter("C:\Users\Ilyas\Desktop\tempBookTitles.txt"); 
PrintWriter pw2 = new PrintWriter("C:\Users\Ilyas\Desktop\duplicateTitles.txt");
// BufferedReader object for input.txt 
BufferedReader br1 = new BufferedReader(new 
FileReader("C:\Users\Ilyas\Desktop\bookTitles.txt")); //read input file
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("C:\Users\Ilyas\Desktop\tempBookTitles.txt"));
BufferedReader br3 = new BufferedReader(new 
FileReader("C:\Users\Ilyas\Desktop\duplicateTitles.txt"));  //try 
String line2 = br2.readLine(); 
// loop for each line of output.txt 
while(line2 != null) 
{ 
if(line1.equals(line2)) 
{ 
line3 = br3.readLine();
flag = true;


if(line1.equals(line3))
{
line1 = null;
}
else
{
pw2.println(line1);
pw2.flush();            
//break; 
}
}
} 
line2 = br2.readLine(); 
} 
// if flag = false 
// write line of input.txt to output.txt 
if(flag==false)
{                                                
pw.println(line1);                   //print to temp file, delete temp file at end
pw.flush(); 
} 
line1 = br1.readLine(); 
} 
br1.close(); 
pw.close(); 
pw2.close();
System.out.println("File operation performed successfully"); 
} 
} 

您应该尝试使程序可读,并通过分解成块的方法使其更小。

请参阅下面我的建议。

private List<String> getAllTitles(String filepath){
List<String> titles = new ArrayList<>();
// read the file, 
// for each of the titles, insert into the list
return titles;
}
private Set<String> getDuplicates(List<String> titles){
Set<String> alreadyReadSet = new HashSet<>();
Set<String> duplicateSet = new HashSet<>();
for (String title : titles) {
if(/*alreadyReadSet contains the title*/){
// put title into duplicateList
}
// put the title into alreadyReadSet
}
return duplicateSet;
}
private void printDuplicateList(Collection<String> duplicateList){
// print to a file
}

要在没有映射的情况下解决它,可以使用方法contains,而不是直接写入输出文件,创建一个输出变量String,并更改

{
pw2.println(line1);
pw2.flush();  
}

对于

if (!output.contains(line1+"n"))
output=output + line1+"n"

并且在循环打印输出到文件之后

所以我相信你现在已经解决了你的问题,但如果其他人遇到这个线程寻求建议。。。

我最近在作业中遇到了同样的问题,试图用我们在课程中迄今为止学到的工具(不包括地图或ArrayList(来解决这个问题让我抓狂。我最终查看了BufferedReader的文档;以及使用mark(int readLimit(和reset((方法。我完成了100%的任务,所以我想我会把这个提示留给其他人。

最新更新