简体   繁体   中英

Sort the integers of a txt file in another file

I have to sort every integers of a file called "file_1.txt" in another file called "file_2.txt", but when I compile it does nothing.

import java.io.*;
import java.util.Scanner;


public static void main(String[] args){

    try
    {   
    Scanner fileScanner = new Scanner(new File("D:\\file_1.txt"));
    while(fileScanner.hasNextLine()){
        Scanner lineScanner= new Scanner(fileScanner.nextLine());
        while (lineScanner.hasNext() && lineScanner.hasNextInt())
        {
            try{
            FileWriter file=new FileWriter("D:\\file_2.txt");
            BufferedWriter writer=new BufferedWriter(file);
            int s = lineScanner.nextInt();
            writer.write(s);
            writer.newLine();
            writer.close();
            file.close();
            }
            catch(FileNotFoundException e){
            e.printStackTrace();
            }
            catch(IOException e){
            e.printStackTrace();
            }

        }lineScanner.close();

    }fileScanner.close();
}

    catch(FileNotFoundException e){
        e.printStackTrace();
    }
}
}

You are opening a file for every line of the first file. You don't want to do that...

Here's the general overview of what you should be doing.

1) Load all numbers from one file into a List.

List<Integer> numbers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("D:\\file_1.txt"));
while(fileScanner.hasNextLine()){
    numbers.add(Integer.parseInt(fileScanner.nextLine());
}

2) Sort the numbers

Collections.sort(numbers);

3) Write the list to a new File

try (PrintWriter pw = new PrintWriter(new File("D:\\file_2.txt"))) {
    for (int x : numbers) {
        pw.println(x);
    }
}

You can read the file into HashSet that will automatically maintain sorted the integers and then write it into another file.

// Hashset maintains the sorted list
Set<Integer> integers = new HashSet<Integer>();
Scanner fileScanner = new Scanner(new File("D:\\file_1.txt"));
while(fileScanner.hasNextLine())
{
    integers.add(Integer.parseInt(fileScanner.nextLine());
}

try (PrintWriter writer = new PrintWriter(new File("D:\\file_2.txt"))) 
{
    for (int integer : integers) 
    {
       writer.println(integer);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM