How do I sort records in a text file using Java?

2020-01-29 11:44发布

问题:

Some amendment of the data in txt file. I have tried the suggested code but Im not successfully write it again in the txt file with this format.I've tried the collection.sort but it write the data in long line.

My txt file contain these data:

Monday
Jessica  Run      20mins
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Tuesday
Mess     Run      20mins
Alba     Walk     20mins
Christy  Jogging  40mins
Bobby    Run      10mins

How can I sort those data in ascending order and store it again in txt file after sorting?

Monday
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins
Tuesday
Alba     Walk     20mins
Bobby    Run      10 mins
Christy  Jogging  40mins
Mess     Run      20mins
Jessica  Run      20mins

回答1:

Here's something I came up with:

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

public class Sort {

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
        Map<String, String> map=new TreeMap<String, String>();
        String line="";
        while((line=reader.readLine())!=null){
            map.put(getField(line),line);
        }
        reader.close();
        FileWriter writer = new FileWriter("fileToWrite");
        for(String val : map.values()){
            writer.write(val);  
            writer.write('\n');
        }
        writer.close();
    }

    private static String getField(String line) {
        return line.split(" ")[0];//extract value you want to sort on
    }
}


回答2:

package com.myFiles;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;

public class FilesReaderWriter {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = null;
        PrintWriter outputStream = null;
        ArrayList<String> rows = new ArrayList<String>();

        try {
            reader  = new BufferedReader(new FileReader("Input.txt"));
            outputStream = new PrintWriter(new FileWriter("Output.txt"));

            String file;
            while ((file = reader .readLine()) != null) {
                rows.add(file);
            }
            Collections.sort(rows);
            String[] strArr= rows.toArray(new String[0]);
            for (String cur : strArr)
                outputStream.println(cur);
        } finally {
            if (reader  != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

}


回答3:

Here's a pretty lazy way of doing it since you are only sorting first word:

    ArrayList<String> rows = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

    String s;
    while((s = reader.readLine())!=null)
        rows.add(s);

    Collections.sort(rows);

    FileWriter writer = new FileWriter("output.txt");
    for(String cur: rows)
        writer.write(cur+"\n");

    reader.close();
    writer.close();


回答4:

Have a class containing 3 parameters : Name , Action , and length.

Open your file for reading , read word by word , for each person create a new instance of the class and fill the appropiate value then insert that instance to some collection.

Sort your collection either by writing you own sort method or (The better option) use one of the Java sorting functions.

Open another file for writing and write your sorted collection in the same fasion.

if you can't translate the above actions into code , Buy the book "Core JAVA" and read it well Or hope someone here will be generous and give you a complete code. :)



回答5:

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

public class Sort1 {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader("fileToRead.txt"));
        Map<String, String> map=new TreeMap<String, String>();
        String line="";
        while((line=reader.readLine())!=null){
                map.put(getField(line),line);
        }
        reader.close();
        BufferedWriter writer = new BufferedWriter(new FileWriter("fileToWrite1.txt"));
        for(String val : map.values()){
                writer.write(val);      
                writer.newLine();
        }
        writer.close();
    }

    private static String getField(String line) {
        return line.split(" ")[0];//extract value you want to sort on
    }
}


回答6:

Using sort:

aaron@ares ~$ sort data.txt 
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins

aaron@ares ~$ sort data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins

... or using python:

aaron@ares ~$ python -c "import sys; print ''.join(sorted(sys.stdin))" < data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt 
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins


回答7:

This solution uses Java 8 Stream API.

Consider that Files.write takes Stream<CharSequence> as the second arg, so we need a type conversion via map(Function.identity()).

import java.io.IOException;
import java.nio.file.*;
import java.util.function.Function;
import java.util.stream.Stream;

public class FileSortWithStreams {

    public static void main(String[] args) throws IOException {
        Path initialFile = Paths.get("files/initial.txt");
        Path sortedFile = Paths.get("files/sorted.txt");

        Stream<CharSequence> sortedLines = Files.lines(initialFile).sorted().map(Function.identity());

        Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
    }
}


回答8:

If there isn't horrible amount of data in that file, try something like this:

load all of its contents into a

String s = <<file contents>>;

String[] strings = s.split(<<here comes lovely regex something like \w+\s\w+\s\w>>);

Arrays.sort(strings);

for (String str : strings) {
  write  str  to your output file;
}

but i am much too tired to propose something more sensible....