如何将数组列表的内容写入文本文件?

时间:2013-01-19 01:16:27

标签: java object arraylist text-files filewriter

我有足够基本的Java程序,要求用户将歌曲输入到音乐库阵列列表中。从那里用户可以随机播放他们的歌曲,删除一首歌曲,删除全部等等。它几乎完成了,我只有一个问题我无法解决。当我尝试将数组列表导出到文本文件时会发生这种情况。而不是数组列表的内容,我的输出看起来像这样,而不是用户提交的详细信息:

“1:MainClass.SongClass@c137bc9 MainClass.SongClass@c137bc9"

我会在下面发布我的代码,如果有人能指出我正确的方向,我真的很感激!

我的最终项目课程,作为我的主要课程:

package MainClass;

import java.io.FileNotFoundException;
import java.util.Scanner;

public class FinalProject extends UserInput {

    public String nextInt;

    public static void main(String[] args) {

//        SongLibrary iTunes;  //Object stores the file cars.txt
//        iTunes = new SongLibrary("MUSIC LIBRARY.txt");
//        songData CLO = iTunes.readFileIntoList();

        UserInput ui;
        ui = new UserInput();

        Scanner input = new Scanner(System.in);

        int opt;



        //Calls Methods Class so methods can be used below
        Menu menuFunctions = new Menu();

        //Calls FileReaderTest Class so file can be read
        SongLibrary Reader = new SongLibrary();

        //initial prompt only displayed when program is first ran
        System.out.println("Welcome to your music library!");


do {

            //Menu Prompts printed to the screen for the user to select from
            System.out.println(" ");
            System.out.println("Main Menu:");
            System.out.println("........ \n"); 
            System.out.println("Press 0 to Exit");
            System.out.println("Press 1 to Add a Song");
            System.out.println("Press 2 to View All Songs");
            System.out.println("Press 3 to Remove a Song");
            System.out.println("Press 4 to Shuffle Library");
            System.out.println("Press 5 to Play a Random song");
            System.out.println("Press 6 to Remove ALL Songs");
            System.out.println("Press 7 to Save Library\n");

            //Monitors the next Int the user types
            opt = input.nextInt();

            //"if" statements
            if (opt == 0) {
                //This corresponds to the condition of the while loop,      
                //The program will exit and print "Goodbye!" for the user.  
                System.out.println(" ");
                System.out.println("Goodbye!");
            } else if (opt == 1) {
                //This method allows the user to add a song to the library.
                //With the format being Title, Artist, Year.
                System.out.println(" ");
                menuFunctions.addEntry();
            } else if (opt == 2) {
                //This method prints the contents of the Array List to the screen  
                System.out.println("\n");
                menuFunctions.viewAll();
            } else if (opt == 3) {
                //This method allows the user to remove an indiviual song from
                //their music library  
                System.out.println("\n");
                menuFunctions.removeOne();
            } else if (opt == 4) {
                //This method uses the Collections.shuffle method
                //to re-arrange the track list
                //song to simulate a music player's shuffle effect.
                System.out.println("\n");
                menuFunctions.shuffleSongs();

            } else if (opt == 5) {
                //This method will clear all contents of the library.
                //It will ask the user to confirm their choice.
                System.out.println("\n");
                menuFunctions.randomSong();
            } else if (opt == 6) {
                //This method will clear all contents of the library.
                //It will ask the user to confirm their choice.
                System.out.println("\n");
                menuFunctions.clearLibrary();
            }   

            else if (opt == 7) {

                try {
                    menuFunctions.saveLibrary();
                } catch (FileNotFoundException x) {
                    System.out.println("File not found. " + x);
                }
            }

            else {
                //If the user selects an incorrect number, the console will 
                //tell the user to try again and the main menu will print again
                System.out.println("\n");
                System.out.println("Incorrect Entry, please try again");
            }


        } //do-while loop
        while (opt > 0);



}

    }

我的SongClass类,它包含构造函数和Get / Set方法

package MainClass;

public class SongClass {

        private int songMinutes;
        private int songSeconds;
        private String songTitle;
    private String songArtist;
    private String songAlbum;
    private int songYear;

public SongClass(int m, int ss, String t, String art, String al, int y){
        songMinutes = m;
                songSeconds = ss;
        songTitle = t;
        songArtist = art;
        songAlbum = al;
                songYear = y;
    }

//GET METHODS

    public int getMinutes() {
        return songMinutes;
    }

    public int getSeconds() {
        return songMinutes;
    }

    public String getTitle() {  //
        return songTitle;
    }
    public String getArtist() {
        return songArtist;
    }
    public String getAlbum() {
        return songAlbum;
    }
    public int getYear() {
        return songYear;
    }

//SET METHODS

    public void setMinutes(int m){
        songMinutes = m;
    }

     public void setDuration(int ss){
        songSeconds = ss;
    }

    public void setTitle(String t){
        songTitle = t;
    }   
    public void setArtist(String art){
        songArtist = art;
    }
    public void setAlbum(String al){
        songAlbum = al;
    }

    public void printSong(){
        System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
    } 

}

我的菜单类包含程序中使用的大部分方法

package MainClass;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class Menu {

    public void add(SongClass s) throws NumberFormatException {
        try {
            songLibrary.add(s);
        } catch (NumberFormatException x) {
        }

    }
    Scanner input = new Scanner(System.in);
    UserInput ui = new UserInput();
    public ArrayList<SongClass> songLibrary;

    public Menu() {
        songLibrary = new ArrayList<SongClass>();
    }

    public void removeOne() throws ArrayIndexOutOfBoundsException {

        try {

        System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
        viewAll();
        //calls the viewAll method to print current library to screen

        int remove = input.nextInt();
        //creates an int that corresponds to the nextInt typed.

        if (remove > songLibrary.size()) {
            System.out.println("Invalid ");
            //if the user types a number higher than the highest index of the
            //array list, they will be shown an error and return to the menu

        }

        else { 
            remove --;
            SongClass s = songLibrary.get(remove);
            System.out.println("Are you sure you would like to delete the following track from your music library? "); 
            s.printSong();
             //confirms user wants to delete the selected track

            System.out.print("1: Yes \n2: No" + "\n");
            int confirmDelete = input.nextInt();
            //Asks the user to input 1 or 2, 

            if (confirmDelete == 1) {
                songLibrary.remove(remove);
                //removes the index of the 4 array lists
                System.out.println( "Removed.");
                viewAll();
            } else if (confirmDelete == 2) {
                System.out.println("\n" + "Okay, the song won't be removed");
            } else {
                System.out.println("\n" + "Invalid option.");
            }

        }
        }
        catch (ArrayIndexOutOfBoundsException x) {
            System.out.println("Please select an valid entry");
        }
    }

    public void clearLibrary() {
        System.out.println("Confirm?");
        System.out.print("1: Yes \n2: No" + "\n");

        int confirmDelete = input.nextInt();
        //if the user types one, this triggers the clear method.

        if (confirmDelete == 1) {
            songLibrary.clear();
            System.out.println("\n" + "Your music library has been cleared" + "/n");
        }

    }

    public void shuffleSongs() {
        //The shuffle function shifts the location of all the elements of an 
        //array list. This mimics the shuffle effect of a Music player
        //The attributes of the song all get shuffled together because they 
        //are all linked by the same seed.

        long seed = System.nanoTime();
        Collections.shuffle(songLibrary, new Random(seed));
        System.out.println("Your library is now shuffled" + "\n");
        viewAll();

        //Shuffles library, then outputs the new library list.
    }

    public void viewAll() {

        if (songLibrary.isEmpty()) {
            System.out.println("Your library is currently empty!");
        } else {

            System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year)  " + "\n");
            for (int i = 0; i < songLibrary.size(); i++) {
                SongClass s = songLibrary.get(i);
                s.printSong();
            }
        }


        System.out.println("\n");
    }

    public void randomSong() {

        int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
        //uses Math.random to generate a random double between 0.0 and 1.0
        //it then multiplies it by the size of the array list - 1
        //The end result is that a random index of the array list is selected

        System.out.println("Now Playing:");
        //the selected song randomSong is then outputted
        //this changes each time the randomSong method is called
        SongClass s = songLibrary.get(randomSong);
        s.printSong();

    }



    public void saveLibrary() throws FileNotFoundException {

        try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
            File inFile = new File("MUSIC LIBRARY.txt");
            Scanner in = new Scanner(inFile);
            System.out.println("Your music library has been successfully exported!\n");
            pw1.println("Your Music Library");
            pw1.println(" ");
            pw1.println("Duration - Artist - Song - Album (Year)  " + "\n");
            pw1.println(" ");

            for (int i = 0; i < songLibrary.size(); i++) {
                System.out.println("The loop ran this many times");
                System.out.println(i);
                int counter = i + 1;
                pw1.println(counter + ": " + songLibrary.get(i));
            }
            System.out.println("Loop is over, PrintWriter should close.");
            pw1.close();
        }
    }



    public void addEntry() throws NumberFormatException {

        try {
            int minutes = ui.getInt("How many minutes does this song last?");
            int seconds = ui.getInt("How many seconds does this song last?");
            String title = ui.getString("What is the title of the track?");
            String artist = ui.getString("Who performs the track?");
            String album = ui.getString("What album is the track from?");
            int year = ui.getInt("What year was the track released?");
            System.out.println("Please enter a number:");
            System.out.println("\n");
            SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
            songLibrary.add(s);
            System.out.println("Thank you!" + " " + title + " " + "was added to your library:");



        } catch (NumberFormatException x) {

            System.out.println(" ");
            System.out.println("Year/Duration can use numbers only, please try again.");
            System.out.println(" ");
        }

    }
}

我的用户输入类

package MainClass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class UserInput{

    private Scanner keyboard;

    public UserInput() {
        this.keyboard = new Scanner(System.in);
    }

    public String getString(String prompt) {
        String line;

        System.out.print(prompt + ": ");
        line = this.keyboard.nextLine();

        return line;
    }

    public int getInt(String prompt) {
        String line;
        int num;

        System.out.print(prompt + ": ");
        line = this.keyboard.nextLine();
        num = Integer.parseInt(line);

        return num;
    }

    public Date getDate(String prompt) {
        String line;
        SimpleDateFormat formatter;
        Date date;

        System.out.print(prompt + " (dd/MM/yyyy): ");
        line = this.keyboard.nextLine();

        formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date = formatter.parse(line);
        }
        catch (ParseException ex) {
            date = null;
        }


        return date;
    }

    public boolean getBoolean(String prompt) {
        String line;

        System.out.print(prompt + "? (Y|N)");
        line = this.keyboard.nextLine();

        return line.equalsIgnoreCase("Y");
    }
}

1 个答案:

答案 0 :(得分:2)

  

“1:MainClass.SongClass@c137bc9 MainClass.SongClass@c137bc9”

这是toString输出的默认实现。

您需要覆盖SongClass中的toString

@Override
public String toString(){
   return String.format("%d:%d - %s - %s - %s - (%d)", 
      songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}

另一种选择(如果你不想覆盖toString可能会更好,因为该方法在别处使用)是遍历列表中的所有元素并通过调用适当的getter(或类似的其他方法)显式格式化输出到你的printSong方法。