First of all I'm sorry if similar questions has been asked before but I couldn't find a solution to what I was looking for. So I've this small java program which compares two text files (text1.txt & text2.txt) and print all the words of text1.txt which doesn't exist in text2.txt. The code below does the job:
text1.txt : This is text file 1. some @ random - text
text2.txt : this is text file 2.
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
public class Read {
public static void main(String[] args) {
Set<String> textFile1 = readFiles("text1.txt");
Set<String> textFile2 = readFiles("text2.txt");
for (String t : textFile1) {
if (!textFile2.contains(t)) {
System.out.println(t);
}}}
public static Set<String> readFiles(String filename)
{
Set<String> words = new HashSet<String>();
try {
for (String line : Files.readAllLines(new File(filename).toPath(), Charset.defaultCharset())) {
String[] split = line.split("\\s+");
for (String word : split) {
words.add(word.toLowerCase());
}}}
catch (IOException e) {
System.out.println(e);
}
return words;
}
}
(Prints word in new line)
Output: @, some, random, 1.
I'm trying to print all the words in alphabetical order. And also if possible, it shouldn't print any specialized character(@,- or numbers). I've been trying to figure it out but no luck. I'd appreciate if someone could help me out with this.
Also I've taken the following line of code from internet which I'm not really familar with. Is there any other easier way to put this line of code:
String line : Files.readAllLines(new File(filename).toPath(), Charset.defaultCharset()))
Edit: HashSet is a must for this piece of work. Sorry I forgot to mention that.