Search code examples
javasortingjava.util.scannermergesort

not able to sort textfile input line by line in an output file


I ran into a problem. I have written following program to sort string of integers in a text file and output the sorted list of integers in an output file. The input file can contain multiple lines of integers and I want to sort them one line at a time and print it out in my output file.

The problem is program reads all the lines from input text and prints out a continuous line of sorted numbers in the output file. How do I make program sort and print sorted list line by line in output file ?

import java.util.*;

import java.io.File;
import java.io.FileNotFoundException;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;


public class MergeSort {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        // declare variable
        int data[];
        int start;
        int end;

        // define the file path that we want to read
        String input_filename = "C:\\Users\\Documents\\NetBeansProjects\\MergeSort\\input.txt";
        String output_file = "C:\\Users\\Documents\\NetBeansProjects\\MergeSort\\output.txt";

        File file = new File(input_filename);

        File outfile = new File(output_file);
        PrintWriter outFile = new PrintWriter(outfile);

        Scanner fileScanner = new Scanner(new FileReader(file));

        while(fileScanner.hasNextLine()){ 

        ArrayList<Integer> list = new ArrayList<Integer>();

        Scanner scanner_second = new Scanner(fileScanner.nextLine());

        while (scanner_second.hasNextInt()) {
            list.add(scanner_second.nextInt());
        }
        int[] intarray = list.stream().mapToInt(Integer::intValue).toArray();

        non_recursive_mergeSort(intarray, 0, intarray.length - 1);

        for (int i = 0; i <= intarray.length - 1; i++) {
            outFile.print(intarray[i] + " ");
        }
      }
        outFile.close();
    } 

Solution

  • You are missing println. Snippet:

            for (int i = 0; i <= intarray.length - 1; i++) {
                outFile.print(intarray[i] + " ");
            }
            outFile.println(); // this is missing
        }
        outFile.close();