如何将输入文件中的行分配给类值的数组?

时间:2015-11-21 20:56:23

标签: java arrays file-io fileinputstream

我想要做的是将输入文件的每一行分配给一个数组值。由于数组是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;
}

1 个答案:

答案 0 :(得分: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());