سؤال

I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:

public static void main(String[] args) {

    String ipt1;
    Scanner fileInput;
    File inFile = new File("input1.dat");

    try {
        fileInput = new Scanner(inFile);
        //Reads file contents
        while (fileInput.hasNext()) {
            ipt1 = fileInput.next();
            System.out.print(ipt1);
        }
        fileInput.close();
    }   
    catch (FileNotFoundException e) {
        System.out.println(e);
    }
}
هل كانت مفيدة؟

المحلول 2

If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.

import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");

try {
    fileInput = new Scanner(inFile);
    //Reads file contents
while (fileInput.hasNext()){
    ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
    System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();

}   
catch (FileNotFoundException e){
    System.out.println(e);
}

//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);

However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:

Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
    actualResult[i] = ipt1.get(i);
}



Arrays.sort(actualResult[]);

نصائح أخرى

I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
    public static void main(String[] args) throws IOException {
        BufferedReader br = null;
        try {
            System.out.println("Started at " + LocalDateTime.now());
            br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
            List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
            Collections.sort(collect);//Sort the data
            writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
            System.out.println("Ended at " + LocalDateTime.now());
        }
        finally {
            br.close();
        }
    }
    public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
        BufferedWriter writer = null;
        File file = new File(filePath);
        try {
            if(!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            writer = new BufferedWriter(new FileWriter(filePath, true));
            if(items != null && items.size() > 0) {
                for(T eachItem : items) {
                    if(eachItem != null) {
                        writer.write(eachItem.toString());
                        writer.newLine();
                    }
                }
            }
        } catch (IOException ex) {
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top