首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用方法将文件内容按字母顺序排序为新文件(Java)

使用方法将文件内容按字母顺序排序为新文件(Java)
EN

Stack Overflow用户
提问于 2021-04-03 10:55:28
回答 1查看 84关注 0票数 1

因此,我正在尝试编写一些代码,以找到一种方法来对以数组的形式收集信息的现有文本文件进行冒泡排序,它如下所示:

04/26/16世嘉3D经典集07/14/16蝙蝠侠:阿卡姆地狱06/24/16东京幻影系列#FE

本质上,我希望它们是按字母顺序排列的,它应该创建一个全新的文件,如下所示:

蝙蝠侠:阿卡姆地狱世嘉3D经典集东京幻影系列#FE

问题是,我不知道如何删除原来是字符串一部分的字符串的日期。我认为应该有类似于javascript中的indexOf()这样的函数。我会假设在提取名字之后。然后,排序将与我为日期排序所做的一样。

这就是我所做的代码:

代码语言:javascript
复制
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("C:/Users/cyrus/Downloads/Lab 11/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("C:/Users/cyrus/Downloads/Lab 11/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("C:/Users/cyrus/Downloads/Lab 11/fileNameSorted1.txt");
    for(String aString:info){
        writer.write(aString);
    }
    writer.close();
}

public static void sortByName(String[]info){
//this isn't really finished, I am unsure on how to extract JUST the name of the games
}
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-03 11:30:00

有几种方法可以对这些行进行排序。假设您将所有行放入一个列表中,并对该列表进行排序,在排序之前,您还将删除日期。使用8

代码语言:javascript
复制
List<String> lines = Arrays.asList("04/26/16  Sega 3D Classics Collection",
                "07/14/16  Batman: Arkham Underworld",
                "06/24/16  Tokyo Mirage Sessions #FE");
        
        List<String> newLines = lines.parallelStream()
                .map(line-> line.substring(line.indexOf(" ")))
                .sorted((line1, line2)->line1.compareTo(line2))
                .collect(Collectors.toList());
newLines.forEach(System.out::println);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66930351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档