Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class Q2_5_9{
- public static class FileSort implements Comparator<FileSort> {
- private String date;
- private long volume;
- public void set(String d, long v) {
- this.date = d;
- this.volume = v;
- }
- abstract class VolCompare{
- public long compare(FileSort obj1, FileSort obj2)
- {
- return obj2.volume - obj1.volume;
- }
- }
- public String getDate() {
- return this.date;
- }
- public long getVolume() {
- return this.volume;
- }
- @Override
- public String toString() {
- return "" + this.date + " " + this.volume;
- }
- //compare method
- public int compare (FileSort obj1, FileSort obj2) {
- int flag = (int) (obj1.volume - obj2.volume);
- if (flag == 0){
- flag = obj1.date.compareTo(obj2.date);
- }
- return flag;
- }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static void main(String[] args) throws IOException {
- ArrayList arrayObjects = new ArrayList<>();
- FileSort fileObject= null;
- String[] splits= new String[2];
- BufferedReader br = null;
- PrintWriter outputStream = null;
- try {
- br = new BufferedReader (new FileReader("Input.txt"));
- outputStream = new PrintWriter(new FileWriter("Output.txt"));
- String line;
- System.out.println("Reading from input.txt ...");
- //when there is a space in the file, split the data to create an object (String, long)
- while((line = br.readLine()) != null)
- {
- fileObject = new FileSort();
- splits = line.split(" ");
- fileObject.set(splits[0], Long.parseLong(splits[1]));
- arrayObjects.add(fileObject);
- }
- System.out.print("Unsorted File: ");
- System.out.println(arrayObjects);
- //Sort the data based on the long
- System.out.println("Sorting the file ...");
- Collections.sort(arrayObjects, new FileSort());
- ArrayList arrayObject = new ArrayList<>();
- arrayObject = arrayObjects;
- System.out.println("Writting the sorted file to output.txt ...");
- for (Object cur : arrayObject) {
- outputStream.println(cur);
- }
- System.out.print("Sorted File: ");
- System.out.println(arrayObjects);
- }
- finally {
- if (br != null) {
- br.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement