Write a program in Java that reads a file of numbers of type int and outputs all
ID: 3549973 • Letter: W
Question
Write a program in Java that reads a file of numbers of type int and outputs all the numbers to another file, but without there being any duplicate numbers. Assume that the input file is sorted from the smallest numbers first to largest numbers last. After the program is run, the new file will contain all the numbers in the original file, but no number will appear more than once in the file. The numbers in the output file should also be listed from smallest to largest. Your program should obtain both file names from the user. This should be done with a text file and a binary file. For the text version of the file, the file should be a text file with one number per line. For the binary version, the file should be a binary file that has numbers of type int that were written using writeInt. Last but not least, the code should catch and handle exceptions when necessary.
Explanation / Answer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.TreeSet;
// Pls ensure correct file path
public class FileNumberSorting {
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new FileReader("d:\oldfile.txt"));
String line;
TreeSet<Integer> set = new TreeSet<Integer>();
while((line=reader.readLine())!=null){
set.add(Integer.parseInt(line));
}
reader.close();
// A set will automatically remove all the duplicates and since it is a treeset
//It will be automatically sorted
File newFile = new File("d: ewfile.txt");
if(newFile.exists()){
newFile.delete();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile, true));
for(Integer i: set){
writer.write(i.toString());
writer.newLine();
writer.flush();
}
writer.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.