java中先读取文本文档,然后对文档中的内容再对“|”后面的数字进行排序,再存入新的文本文档

我的数据是这样的A|3000B|5000C|1000D|2000E|9000F|6000
2025-05-18 03:59:04
推荐回答(1个)
回答(1):

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class SortStringDemo {

  public static void main(String[] args) throws IOException {
    
    //读取文本数据
    File file = new File("1.txt");
    List list = new ArrayList<>();
    
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
      String temp = scanner.nextLine();
      if (!temp.equals("")) {
        list.add(temp);
      }
    }
    scanner.close();
    
    
    // sub字符串,再使用Integer.comparTo() 如:1 2 11 这种数字大小排序
    Collections.sort(list, new Comparator() {
      @Override
      public int compare(String o1, String o2) {
        Integer n1 = Integer.valueOf(o1.substring(o1.indexOf("|") + 1, o1.length()));
        Integer n2 = Integer.valueOf(o2.substring(o2.indexOf("|") + 1, o2.length()));
        return n1.compareTo(n2);
      }
    });
    System.out.println("按照数字大小排序:\t" + list);

    // sub字符串,再使用String.comparTo() 如:1 11 2 这种按照字符串序号排序
    Collections.sort(list, new Comparator() {
      @Override
      public int compare(String o1, String o2) {
        String string1 = o1.substring(o1.indexOf("|") + 1, o1.length());
        String string2 = o2.substring(o2.indexOf("|") + 1, o2.length());
        return string1.compareTo(string2);
      }
    });
    System.out.println("按照子串排序:\t" + list);
    
    //存储文本数据
    File file2 = new File("2.txt");
    PrintWriter pw = new PrintWriter(file2);
    for (int i = 0; i < list.size(); i++) {
      pw.println(list.get(i));
    }
    pw.close();
  }
}