从逗号分隔的 ArrayList 写入文本文件

Writing to Text File from Comma Delimited ArrayList

我创建了一首歌曲 class,其中包含歌曲的数据成员(标题、艺术家、专辑、长度)。我已经有一个 .txt 文件,其中包含存储在数组列表中的不同歌曲。用户完成添加或删除歌曲后,程序应以文本文件的原始格式(逗号分隔)写入文本文件。

我的问题是程序写入文件时没有逗号,当我 re-run 它通过获取 ArrayIndexOutOfBoundsException 导致我的程序崩溃。我曾尝试使用嵌套 for-loops 和 printf 函数,但没有成功。如何以原始格式写入文件并避免在写入文件并再次尝试 运行 后崩溃?

这是 .txt 文件的格式
岩龙虾,B-52's,B-52's,4:37
像埃及人一样走路,手镯,不同的光线,3:24

这是我的歌曲 Class 使用 toString() 方法

public class Song {
    //Declaring all data members.
    private String title;
    private String artist;
    private String album;
    private String length;
    private static int songCounter = 0;

    //Constructors for Song class.      
    public Song(String title, String artist, String album, String length){
        this.title = title;
        this.artist = artist;
        this.album = album;
        this.length = length;
        songCounter++;
    }
    //Get and Set methods 
    public String getTitle(){
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getArtist(){
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getAlbum(){
        return album;
    }

    public void setAlbum(String album){
        this.album = album;
    }

    public String getLength(){
        return length;
    }

    public void setLength(String length){
        this.length = length;
    }

    public static int getSongCounter(){
        return songCounter;
    }
    public int compareArtist(Song o){
        return artist.compareTo(o.artist);
    }
    public int compareTitle(Song o){
        return title.compareTo(o.title);
    }
    //Overriding the toString() function.
    @Override
    public String toString(){
        return title +","+artist+","+album+","+length;
    }
}      

这是我的 Main Class,它从文件中读取并包含一个写入方法

public class Library {

public static void main(String[] args) {
    ArrayList <Song> songList = new ArrayList <Song> ();
    boolean repeat = true;

    try{
        Scanner read = new Scanner (new File("SongList.txt"));
        do{
            String line = read.nextLine();
            String [] tokens = line.split(",");
            songList.add(new Song(tokens[0], tokens[1], tokens[2], tokens[3]));
        }while(read.hasNext());
        read.close();
    }catch (FileNotFoundException e){
        System.out.println("File not found.");
    }

    while ( repeat ){
        System.out.println("\nSelect a Function");
        System.out.println("1. Search Song");
        System.out.println("2. Add Song");
        System.out.println("3. Delete Song");
        System.out.println("4. Display Songs");
        System.out.println("5. Quit");

        switch (MenuInputCheck(1, 5)){

        case 1: searchSong(songList);
                break;
        case 2: addSong(songList);
                break;
        case 3: deleteSong(songList);
                break;
        case 4: displaySorted(songList);
                break;
        case 5: saveFile(songList);
                repeat = false;
                break;
        }
    }
}

public static void saveFile(ArrayList <Song> songList){
    try{
        PrintWriter writer = new PrintWriter("SongList.txt");
        for (int i = 0; i < songList.size();i++){
            writer.println(i);
        }
        writer.close();
    } catch (FileNotFoundException e){
        System.out.println("File not found.");
    }
}

您正在将 i 的值写入文件??你应该写歌曲信息。你Song class 不在,我只是在补字段和方法

如果您使用的是 Java 8,则可以使用 StringJoiner API...

public static void saveFile(ArrayList <Song> songList){
    try{
        PrintWriter writer = new PrintWriter("SongList.txt");
        for (Song song : songList){
            StringJoiner sj = new StringJoiner(",");
            sj.add(song.getTitle());
            sj.add(song.getArtiest());
            sj.add(song.getAlbum());
            sj.add(song.getDuration());
            writer.println(sj.toString());
        }
        writer.close();
    } catch (FileNotFoundException e){
        System.out.println("File not found.");
    }
}

否则,您将需要使用 String#formatStringBuilder 之类的东西来生成输出...

现在可能是时候向您介绍 JAXB...

已更新

因此,根据您更新的代码,包括 Song class,您应该能够做一些简单的事情,例如...

public static void saveFile(ArrayList <Song> songList){
    try{
        PrintWriter writer = new PrintWriter("SongList.txt");
        for (Song song : songList){
            writer.println(song.toString());
        }
        writer.close();
    } catch (FileNotFoundException e){
        System.out.println("File not found.");
    }
}

目前代码只是写一个 integer

 for (int i = 0; i < songList.size();i++){
        writer.println(i);
 }

我建议您在 Song 中创建一个方法,它将写入由逗号分隔的字段

例如

public String writeMe () {
   StringBuffer buf = new StringBuffer ();
   buf.append (name).append(",").append(artist).....;

   return buf.toString ();

}

然后在你的循环中调用

writer.write (singList.get(i).writeMe ();

更新

使用您更新的代码,您可以使用

获得输出
writer.println(song.toString());