I'll help you create a Java program that reads a text file and removes duplicate links. Here's a solution that accomplishes this:
import java.io.*;
import java.util.*;
public class LinkDeduplicator {
public static void main(String[] args) {
// Input and output file paths
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
try {
// Read the input file
List<String> links = readLinksFromFile(inputFilePath);
// Remove duplicates
Set<String> uniqueLinks = new LinkedHashSet<>(links);
// Write unique links to output file
writeLinksToFile(outputFilePath, uniqueLinks);
System.out.println("Duplicate links removed successfully!");
System.out.println("Total unique links: " + uniqueLinks.size());
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
// Method to read links from file
private static List<String> readLinksFromFile(String filePath) throws IOException {
List<String> links = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
// Trim whitespace and add non-empty lines
if (!line.trim().isEmpty()) {
links.add(line.trim());
}
}
}
return links;
}
// Method to write unique links to output file
private static void writeLinksToFile(String filePath, Set<String> uniqueLinks) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (String link : uniqueLinks) {
writer.write(link);
writer.newLine();
}
}
}
}
This program does the following:
-
Reading the File:
- The
readLinksFromFile() method reads links from the input text file.
- It trims each line and removes empty lines.
-
Removing Duplicates:
- Uses a
LinkedHashSet to automatically remove duplicates while maintaining the original order.
-
Writing Unique Links:
- The
writeLinksToFile() method writes the unique links to an output file.
How to Use:
- Save the input links in a text file named
input.txt (one link per line).
- Run the program.
- The unique links will be saved in
output.txt.
Additional Features:
- Preserves the original order of links
- Removes whitespace
- Handles potential IO exceptions
- Prints the total number of unique links
Example Input File (input.txt):
https://www.example.com
https://www.google.com
https://www.example.com
https://www.github.com
https://www.google.com
Example Output File (output.txt):
https://www.example.com
https://www.google.com
https://www.github.com
You can customize the file paths in the main() method if needed. The program will print the number of unique links and confirm successful deduplication.