【问题标题】:How do I assign lines from an input file to an array of a class value?如何将输入文件中的行分配给类值数组?
【发布时间】:2015-11-21 20:56:23
【问题描述】:

我想要做的是将输入文件的每一行分配给一个数组值。由于数组是 Song[] 类型,我不知道该怎么做。

public int readMusicCollection(Song[] array, String filename) {
    int count = 0;
    Scanner inputStream = null;

    try {
        inputStream = new Scanner(new File(filename));
    } catch (FileNotFoundException e) {
        System.out.println("Cannot open input file: " + filename);
    }

    while (inputStream.hasNextLine()) {
        array[count] = inputStream.nextLine();
    }

    return count;
}

【问题讨论】:

  • Song类的代码怎么样?你能把它放在这里吗?
  • 字符串(通过 nextLine 得到的)不能分配给 Song[] 数组元素。 必须知道一行如何表示一个 Song 对象,并且必须编写代码来从一个字符串创建一首 Song。

标签: java arrays file-io fileinputstream


【解决方案1】:

基本上,您想读取文件的每一行并将其转换为歌曲:

public static List<Song> readMusicCollection(String filename) {
    List<String> allLines = Files.readAllLines(new File(filename).toPath());
    // convert to Song:
    List<Song> songs = new ArrayList<>(allLines.size());
    for(String line : allLines) {
        Song song = // convert line to Song
        songs.add(song);
    }
    return songs;
}

使用 Java 8:

List<Song> songs = 
    Files.lines(new File(filename).toPath())
         .map(line -> transformToSong(line))   // TODO: implement transformToSong
         .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2017-05-17
    • 2013-11-20
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 2013-02-09
    • 2019-02-24
    相关资源
    最近更新 更多