Search code examples
javafile-ioarraylistdelimiterprintwriter

Writing to Text File from Comma Delimited ArrayList


I have created a Song class that includes data members for a Song (Title, artist, album,length). I already have a .txt file that contains different songs which is stored into an array list. After the user finishes adding or deleting songs the program should write to the text file in the original format of the text file (comma separated).

My problem is that the program writes to the file without the commas and it is causing my program to crash when I re-run it by getting an ArrayIndexOutOfBoundsException. I have attempted to use nested for-loops and the printf function but have had no success. How can i write to the file with its original formatting and avoid crashing after i write to it and attempt to run it again?

This is the format of the .txt File
Rock Lobster,The B-52's,The B-52's,4:37
Walk Like An Egyptian,The Bangles,Different Light,3:24

This is my Song Class with toString() method

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;
    }
}      

This is my Main Class that reads from the file and contains a write method

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

Solution

  • presently the code is simply writing an integer

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

    I suggest you create a method in Song which will write its fields sperated by commas

    e.g.

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

    }

    and then in your loop call

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

    Update

    Using you updated code you can get the output using

    writer.println(song.toString());