簡體   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