从java中的多个文本文件中检索数据

时间:2014-12-21 14:58:42

标签: java arrays io inputstream

我正在尝试从多个文本文件(比如歌曲)中检索数据并将它们记录到一个数组中。问题是,所有数组值都具有LAST FILE的值。这是代码的一部分

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

1 个答案:

答案 0 :(得分:0)

您还没有包含所有方法的代码。您发布的代码将抛出NullPointerException,因为new Song[no]创建一个新数组,其值全部为null。第一次遇到song[i].artist = …时,song [i]将为null并抛出异常。

我的猜测是,您的实际代码(我们无法看到)仅调用new Song()一次,然后执行以下操作:

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

这会导致数组的所有元素指向相同的实例。它不会创建20个Song对象,它只会创建20个对一首Song的引用。所以你的循环访问正确的数组元素,但每次,该数组元素都指向同一个Song对象。

正确的做法是将此行放在循环中:

song[i] = new Song();