简体   繁体   中英

Retrieving data from multiple text files in java

I'm trying to retrieve data from multiple text files(say songs) and record them into an array. The problem is, all array values have the LAST FILE's values. Here's a part of code

  public static Song[] retrieve(String path, String type, String g, int no)

       {
        Song[] song;
        song = new Song[no];

        Scanner s;
        String lrc = "";

        for(int i=0;i<no;i++)
        {
            try
            {
                s = new Scanner(new FileInputStream(path+"\\"+type+"\\"+g+"\\"+(i+1)+".txt"));

                song[i].artist = s.nextLine();
                song[i].title = s.nextLine();
                song[i].genre = "ARB";
                while(s.hasNext())
                    lrc = lrc + " " + s.next();
                song[i].lyrics = lrc.split(" ");
                lrc = "";
                s.close();
                /*System.out.println(song[i].artist);
                System.out.println(song[i].title);
                System.out.println(song[i].genre);
                for(int j = 0; j < song[i].lyrics.length; j++)
                    System.out.print(song[i].lyrics[j]+" ");
                System.out.println("")*/

            } catch(FileNotFoundException e)
            {
                System.out.println("File not found");
            }
        }

        return song;
    }

You haven't included all of your method's code. The code you have posted would throw a NullPointerException, because new Song[no] creats a new array whose values are all null. The first time song[i].artist = … is encountered, song[i] would be null and the exception would be thrown.

My guess is that your actual code (which we can't see) is calling new Song() only once, and then is doing something like this:

Song newSong = new Song();
for (int z = 0; z < no; z++) {
    song[z] = newSong;
}

That causes all elements of the array to point to the same instance. It doesn't create 20 Song objects, it just creates 20 references to one Song. So your loop is accessing the right array element, but each time, that array element is pointing to the same Song object.

The correct thing to do is to put this line inside your loop:

song[i] = new Song();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM