简体   繁体   中英

How to sort data from multiple files in java

I am currently playing around with java and I am wondering if it is possible to read from a few files, and then sort the contents from all of them (alphabetically)?

If that is possible would I be able to take an entire line, and sort it based on the first phrase?

Example:

This,

ECE3111 A- 4.00

ECE3031 A- 4.00

CS1003 B+ 4.00

Would return this,

CS1003 B+ 4.00

ECE 3031 A- 4.00

ECE3111 A- 4.00

The names will always have length 6 to 8 so is there a way of only sorting a line based on the first n number of places in the string?

Any tips would be greatly appreciated.

Yes, it is possible. In order to do this, you would need to follow this general flow:

  • Create a list to store each line in
  • Read first file (with a BufferedReader ), storing line by line into the list
  • Repeat above for each file
  • Sort list of lines (can be done natively using Java 's Collections library with Collections.sort(Collection<T> c)
  • Output each line from files, or process it as you need

First, create your list:

List<String> lines = new ArrayList<String>();

While we are reading the files, we will add each line to this list so we can store it, sort it, and output it later. Next, we need to read in each file and store it. A good guide on reading in files line by line in java can be found here . I will do this with 1 file using a BufferedReader and the technique in the previous link. You can do this with multiple files by looping over the list of files that you need to read from.

    BufferedReader fileReader = new BufferedReader(new FileReader("text.txt")); // Create reader with access to file
    String fileLine = fileReader.readLine(); // Read the first line
    while (fileLine != null) { // While there are still lines to read, keep reading
        lines.add(fileLine); // Store the current line
        fileLine = fileReader.readLine(); // Grab the next line
    }
    fileReader.close(); // Read all the lines, so close the read

The above code will read every line from the file text.txt and add it to the list that was created. Now we can use the Java Collections library, and sort the list of lines using that. This can be done by calling Collections.sort(obj) . So, with our code, we call:

Collections.sort(lines);

Now, inside of our lines list variable, we have a sorted list of all of the lines in the file(s) that we read. Now you can do whatever you need to with this sorted list ! I decided to just output it.

    for(String line : lines){
        System.out.println(line);
    }

The full code is:

public static void main(String[] args) throws Exception {


    List<String> lines = new ArrayList<String>();

    BufferedReader fileReader = new BufferedReader(new FileReader("text.txt")); // Create reader with access to file
    String fileLine = fileReader.readLine(); // Read the first line
    while (fileLine != null) { // While there are still lines to read, keep reading
        lines.add(fileLine); // Store the current line
        fileLine = fileReader.readLine(); // Grab the next line
    }
    fileReader.close(); // Read all the lines, so close the read

    Collections.sort(lines);
    for(String line : lines){
        System.out.println(line);
    }

}

I ran this code on the file text.txt which contained:

ECE3111 A- 4.00
ECE3031 A- 4.00
CS1003 B+ 4.00

And I got the output:

CS1003 B+ 4.00
ECE3031 A- 4.00
ECE3111 A- 4.00

To get all files in a directory, we can create a list of String variables that represent a file's name. Then, loop over all files in a directory and check that they end with the extension that you are looking for.

    List<String> textFileNames = new ArrayList<String>();
    File directory= new File("StackTxtFiles"); // Point to your directory you want to search
    for (File file : directory.listFiles()) // Loop over everything that exists in the directory
    {
       if (file.getName().endsWith(".txt")) // if the extension is ".txt", it's a text file so we should include it
       {
           textFileNames.add(file.getName()); // Add the file's name to the included list
       }
    }

Then, in your code for reading the files, put it inside of a loop looping over the textFileNames list and use the String variable as the file name passed into the FileReader rather than a hard-coded value.

    List<String> lines = new ArrayList<String>();
    for(String fileName : textFileNames){ // Loop over each file that we found in the directory searching
        BufferedReader fileReader = new BufferedReader(new FileReader("StackTxtFiles/"+fileName)); // Create reader with access to file. Add the directory we are looking in
        String fileLine = fileReader.readLine(); // Read the first line
        while (fileLine != null) { // While there are still lines to read, keep reading
            lines.add(fileLine); // Store the current line
            fileLine = fileReader.readLine(); // Grab the next line
        }
        fileReader.close(); // Read all the lines, so close the read
    }

Yes it is possible.

I would recommend loading all the Strings into an ArrayList<String> , call Collections.sort(<List name>); and then use an enhanced for loop to write it out to the file of your choosing.

Hope this Helps!

You can use a TreeSet with a comparator of your choice.

So Set A could have a comparator that compares the entire words.

Set B could have a comparator that compares only the first 3 letters (substring) of the word.

Then you just iterate through the files, add them to your sets, and you're done.

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