简体   繁体   English

使用方法(Java)按字母顺序对文件内容进行排序

[英]Alphabetically sort contents of file using methods (Java)

The title might be a little misleading but I am writing a piece of code that has this as the contents of the text file:标题可能有点误导,但我正在编写一段代码,将其作为文本文件的内容:

 04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE

Essentially I want them to be in alphabetical order and it should make a brand new file that looks like this:本质上,我希望它们按字母顺序排列,它应该创建一个如下所示的全新文件:

 Batman: Arkham Underworld Sega 3D Classics Collection Tokyo Mirage Sessions #FE

What I have tried is to use the indexOf() method to extract only the names of the list of games from my existing text file.我尝试的是使用 indexOf() 方法从我现有的文本文件中仅提取游戏列表的名称。 I have also tried to store them in a new array to avoid confusion for the computer.我还尝试将它们存储在一个新数组中以避免计算机混淆。 The problem is that when I try to store the indexOf of the info array into a new array, the line gives an error of "cannot convert from int to string" and I am not sure on how to fix the error.问题是,当我尝试将 info 数组的 indexOf 存储到新数组中时,该行给出了“无法从 int 转换为字符串”的错误,我不确定如何修复该错误。

This is my code below:这是我下面的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main{
  public static void main (String[]args) throws IOException{

    File file = new File("releasedates.txt");

    String []arr = input(file);

    output(file,arr);

    outputSort1(file, arr);
    

  }

  public static String[]input (File file) throws FileNotFoundException{
    String[]arr = new String[3];
    Scanner sc = new Scanner(file);

    for(int i = 0; i < arr.length; i++){
      arr[i] = sc.nextLine();

    }
    return arr;
  }

  public static void output(File file, String[] info) throws IOException{

    FileWriter writer = new FileWriter("fileName.txt");
    for(String aString:info){
      writer.write(aString);
    }
    writer.close();
  }

  public static void sortByMonth(String[]info){

    String temp;

    for (int j = 0; j < info.length; j++) {
      for (int i = j + 1; i < info.length; i++) {
 
  if (info[i].compareTo(info[j]) < 0) {
    temp = info[j];
    info[j] = info[i];
    info[i] = temp;
        }
     }
    }
  }

  public static void outputSort1(File file,String[] info) throws IOException{
    sortByMonth(info);
    FileWriter writer = new FileWriter("fileNameSorted1.txt");
    for(String aString:info){
        writer.write(aString);
    }
    writer.close();
}

public static void sortByName(String[]info){

    String[] names = new String[3];

      for(int i = 0; i < info.length; i ++){

          names[i] = info[i].indexOf(" " ,info.length);
      }

    String temp;

      for (int j = 0; j < names.length; j++) {
        for (int i = j + 1; i < names.length; i++) {
   
    if (names[i].compareTo(names[j]) < 0) {
      temp = names[j];
      names[j] = names[i];
      names[i] = temp;
          }
       }
      }
    }

}

You've declared names array as String[] so you can't assign integer to it.您已将名称数组声明为String[] ,因此您不能将 integer 分配给它。 indexOf method returns integer. indexOf 方法返回 integer。

public static void sortByName(String[]info) {
    String[] names = new String[3];   //<-- declaration suggests store string
    for (int i = 0; i < info.length; i++) {
        names[i] = info[i].indexOf(" ", info.length);//<-you are assigning integer
    }

I think what you are trying to do is like this:我认为你正在尝试做的是这样的:

names[i] = info[i].substring(info[i].indexOf(" "), info[i].length());

Use java.nio APIs for file implementations as java.io apis are outdated.使用java.nio API 进行文件实现,因为java.io API 已过时。 Also, if you use Stream operations then the implementation becomes much easier:此外,如果您使用 Stream 操作,那么实现会变得容易得多:

public class Test {
    public static void main(String[] args) throws Exception {
        Path file = Path.of("e:\\releasedates.txt");
        List<String> records = Files.readAllLines(file);

        List<String> sortedByName = records.stream()
                .map(s -> s.substring(s.indexOf(" "), s.length()))
                .sorted(String::compareTo)
                .collect(Collectors.toList());
        System.out.println(sortedByName);
        Files.write(Path.of("e:\\fileNameSorted.txt"), sortedByName);

        List<String> sortedByDate = records.stream().sorted(Test::compareDates)
                .map(s -> s.substring(s.indexOf(" "), s.length()))
                .collect(Collectors.toList());
        System.out.println(sortedByDate);
        Files.write(Path.of("e:\\fileDateSorted.txt"), sortedByDate);
    }

    public static int compareDates(String d1, String d2) {
        d1 = d1.substring(0, d1.indexOf(" "));
        d2 = d2.substring(0, d2.indexOf(" "));
        LocalDate ld1 = LocalDate.parse(d1,
                DateTimeFormatter.ofPattern("MM/dd/yy"));
        LocalDate ld2 = LocalDate.parse(d2,
                DateTimeFormatter.ofPattern("MM/dd/yy"));

        return ld1.compareTo(ld2);
    }
}

Answer by @onkar ruikar is correct. @onkar ruikar 的回答是正确的。 indexOf returns int and you are trying to store it in String . indexOf返回int并且您试图将其存储在String中。 I would like to extend his answer, where you can store the game/movie names in TreeSet instead of Array , so that by default it will be sorted in alphabetical order.我想扩展他的答案,您可以将游戏/电影名称存储在TreeSet而不是Array中,因此默认情况下它将按字母顺序排序。

If you want to allow duplicate game/movie names, then you can use ArrayList and call Collections.sort(<array list>) method, which will sort the ArrayList in alphabetical order.如果您想允许重复的游戏/电影名称,则可以使用ArrayList并调用Collections.sort(<array list>)方法,该方法将按字母顺序对ArrayList进行排序。

Here is the detailed answer of how can we sort Collections in Java: https://stackoverflow.com/a/8725470/3709922这是我们如何在 Java 中对Collections进行排序的详细答案: https://stackoverflow.com/a/8725470/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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