【问题标题】:Saving array in multiple txt files depending on their content in Java根据 Java 中的内容将数组保存在多个 txt 文件中
【发布时间】:2020-08-21 19:32:18
【问题描述】:

基本上,我有创建多个音乐专辑的主要方法:

Album[] tabA = {new Album ("AAAAA", 0, 1960, 60, 0, "maison", "BBBB", true),
                    new Album ("CCCCC", 1, 1961, 61, 0, "maison", "DDDD", true),
                    null,
                    new Album ("EEEEE", 2, 1962, 62, 1, "maison", "FFFF", false),
                    new Album ("GGGGG", 3, 1963, 63, 1, "maison", "HHHH", true),
                    null,
                    new Album ("IIIII", 4, 1964, 64, 0, "maison", "JJJJ", false),
                    new Album ("KKKKK", 5, 1970, 70, 1, "maison", "LLLL", true),
                    new Album ("MMMMM", 6, 1971, 71, 1, "maison", "NNNN", true) };

我现在想要的是根据以下方法中的第 5 个信息(0 或 1)将这些专辑保存在 2 个单独的 txt 文件中

saveAlbums(tabA);//call for the method inside the main method


public static void saveAlbums ( Album[] tab){


}

感谢任何帮助!

【问题讨论】:

  • Album 是否覆盖toString() 方法?到目前为止,您尝试过什么?

标签: java arrays file methods save


【解决方案1】:

您必须迭代选项卡的元素,并使用 getter 查看第 5 个元素的性质,以决定哪个 txt 文件,如下所示:

public static void saveAlbums ( Album[] tab){
for(Album t : tab){
   if ( t.getyourelement() == 1 ) // save in your first txt file
   if ( t.getyourelement() == 0 ) // save in your second txt file
}
}

【讨论】:

    【解决方案2】:

    不知道你在问什么,但这里是完整的细节。

    private static saveAlbums(Album[] albums) {
        List<Album> zeroList = new ArrayList<>();
        List<Album> oneList = new ArrayList<>()
    
        for (Album album : albums) {
            if (album != null) {
                if (album.getValueNumberFive() == 0) {
                    zeroList.add(album);
                } else {
                    oneList.add(album);
                }
            }
        }
    
        writeFile("Album-Zero.txt", zeroList);
        writeFile("Album-One.txt", oneList);
    }
    
    public static void writeFile(String filename, List<Album> albumList) {
        Writer output = null;
        File resultFile = new File(filename);
        try {
            output = new BufferedWriter(new FileWriter(resultFile));
            for (Album album : albumList) {
                output.write(album.toString());
            }
            output.flush();
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            safeClose(output);
        }
    }
    

    【讨论】:

    • 您的Lists 应声明为List&lt;Album&gt;
    • 好收获。就像在 writeFile 参数中一样。固定。
    猜你喜欢
    • 2015-12-10
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多