简体   繁体   English

从文件中获取数字并对其进行排序

[英]Take numbers from a file and sort them

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);
    }
}

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.我建议使用 fileInput.nextInt() 或您想要的任何类型将值读取为数字类型,将它们放入数组并使用内置排序,如 Arrays.sort。 Unless I'm missing a more subtle point about the question.除非我错过了关于这个问题的更微妙的一点。

If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.如果您的任务只是从某个文件中获取输入并且您确定该文件具有整数,请使用 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:但是,如果您确实需要最终想出一个简单的数组,但可以使用 ArrayLists,则可以添加以下内容:

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



Arrays.sort(actualResult[]);
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文件中读取数字并在 java 中对它们执行操作? - How to read numbers from file and take actions on them in java? Java - Eclipse - 从文件中获取名称和数字,按字母顺序排序到新文件中,以数字方式排序为新文件 - Java - Eclipse - Take names and numbers from a file, sort alphabetically into a new file, sort numerically into a new file 从字符串数组索引中获取数字,并将它们相乘? - Take numbers from string array index, multiply them together? 如何从字符串中取数字并将它们放入arrayList中 - How to take numbers from a string and put them into an arrayList 从txt文件中读取数字并进行比较 - Reading numbers from a txt file and comparing them 从Java中的文件冒泡排序数字 - Bubble Sort numbers from file in java 我需要在文本文件中采用三行数组,并根据Java中的第一行对其进行排序 - I need to take an array of three lines in a text file and sort them base on the first line in Java 从文本文件中获取值并将其放入数组中 - Take values from a text file and put them in a array 从我的队列中取出数字即String并将其加在一起,以便可以打印出结果 - Take String that is numbers from my queue out and add them together so can print out the result 使用简单的数组对数字进行堆叠? - Using simple arrays to sort numbers by stacking them?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM