繁体   English   中英

Java:如何将两个 .txt 文件合并为一个?

[英]Java: How to merge two .txt files into one?

对于这个程序,我必须合并两个文件,一个包含学生姓名和 ID 号,另一个包含班级 ID 代码。 然后,我必须将学生的 ID 代码与班级的 ID 代码进行匹配,并按字母顺序将它们分类到一个新的班级名册中。

我必须使用数组和二进制搜索。

我真的不确定该怎么做。 我没有太多,但我有的是:

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

public class MergingFiles {


  public static void main(String[] args) throws IOException { 
    Scanner studentFile = new Scanner(new File("students.txt"));
    Scanner classFile = new Scanner(new File("classes.txt"));

    while (studentFile.hasNext()){
     }
    while (classFile.hasNext()){
     }
      //as long as another line, keeps running
      //sort students alphabetically
      //2 substrings, one id #, one students
      //read id codes, match with name
      //create new roster file


  }



}

我知道我需要将内容放入一个数组中,但是什么样的数组以及我将如何编写它?

任何帮助表示赞赏。

谢谢。

怎么样:

1.) 使用变量nameid创建一个Student

2.) 扫描学生列表时,将他们添加到Student[] 数组不能调整大小(而且似乎不允许使用列表),所以想想你如何知道数组的大小,这样你就不必调整它的大小(除非你想添加动态调整数组大小的代码,这也是可行的)。

3.) 对Student[]排序(二进制搜索的要求)。 如果必须手动执行此操作,则必须编写自己的排序实现(考虑要比较Student对象的哪个字段)。 如果您被允许使用 API 排序方法(并且您已经涵盖了接口),那么只需让Student实现Comparable然后调用Arrays.sort

4.) 在扫描类文件时,我假设您需要在此处使用二进制搜索来查找Student (基于他们的 id),但我不确定输入文件的格式,所以我不确定当然我可以给你更多的指导。

尝试这个

 public static File mergeAllFiles(File[]files,File dest) throws IOException{
    List<String> paths = 
   Stream.of(files).map(File::getPath).collect(Collectors.toList());
    for (String string : paths) {
        List<String> allLines = Files.readAllLines(Paths.get(string));
        Files.write(Path.of(dest.getPath()),allLines, StandardOpenOption.APPEND);
    }
    return dest;
}

暂无
暂无

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

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