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

时间:2015-02-27 04:57:27

标签: java file-io arraylist delimiter printwriter

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

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

这是.txt文件的格式
Rock Lobster,B-52&B,B-52& s,4:37
像埃及人一样走路,手镯,不同之光,3:24

这是我的Song Class with 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;
    }
}      

这是我从文件中读取并包含写入方法的主类

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.");
    }
}

2 个答案:

答案 0 :(得分:0)

您正在将i的值写入文件?你应该写歌曲信息。在您Song课程的缺席中,我只是编写字段和方法

如果您使用的是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类),您应该可以做一些简单的事情......

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.");
    }
}

答案 1 :(得分:0)

目前代码只是编写integer

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

我建议您在Song中创建一个方法,用于编写以逗号分隔的字段

e.g。

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());