Bao
Bao

Reputation: 23

Read file, sort it, write to another file

For my assignment, I have to read from a file with 25 numbers, then sort it in order, then write it to another file. I can't think of a way to pass the array in my code (to the the string of an array) to write the file in order and for it to write the numbers to a different file.
This is probably a simple question but I am just having a little trouble trying to pass everything. Thank you in advance.

public static void main(String[] args) throws IOException{
    int[] number;
    number = processFile ("Destination not specified");
    swapIndex(number);
    writeToFile ("Destination not specified");

}

public static int[] processFile (String filename) throws IOException, FileNotFoundException{

    BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));

    String line;
    int i = 0;
    int[] value = new int [25];
    while ( (line = inputReader.readLine()) != null){
    int num = Integer.parseInt (line);      // Convert string to integer.
           value[i] = num;    
            i++;
            System.out.println (num); // Test 
    }
    inputReader.close (); 
    return value;
    // Read the 25 numbers and return it
}

public static void swapIndex (int[] num){   // BUBBLE sort
    boolean order = true;
    int temp;

    while (order){
        order = false; 
        for (int i = 0; i <num.length-1; i++){
            if (num[i]> num[i+1]){
                temp = num[i]; //set index to temp
                num[i] = num [i+1]; // swap
                num[i+1]= temp; //set index to the higher number before it
                order = true;
            }
        }
    }          
} // Method swapIndex

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));

       outputWriter.write (String.valueOf ()); // Need to take the string value of the array
       outputWriter.flush(); 
       outputWriter.newLine ();
}

Upvotes: 1

Views: 1755

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

I would do it this way

    Set<Integer> set = new TreeSet<Integer>();
    Scanner sc = new Scanner(new File("1.txt"));
    while (sc.hasNextInt()) {
        System.out.println(sc.nextInt());
    }
    sc.close();
    PrintWriter pw = new PrintWriter(new File("2.txt"));
    for (int i : set) {
        pw.println(i);
    }
    pw.close();

Upvotes: 1

phani diva
phani diva

Reputation: 1

Instead of swapIndex(number) you used to sort the integer array, you could use Arrays.sort(number) and then pass this integer array(number) as one of the arguments to writeToFile method, iterate over those elements of integer array(number) and can add to the file.

Upvotes: 0

Related Questions