2015-08-14 81 views
0

我正在制作一个程序,用于将歌曲的标题,艺术家和流派存储到数据文件中。就像这样:运行程序后保留一个值?

public void writeSong(Song t) throws IOException { 
    File myFile = new File(Song.getFileInput()); 
    RandomAccessFile write = new RandomAccessFile(myFile,"rw"); 
    write.writeChars(title); 
    write.writeChars(artist); 
    write.writeChars(genre); 
    write.close(); 
} 

后,我这样做,我应该读取数据文件,并显示它的内容是这样的:

public Song readSong() throws FileNotFoundException, IOException { 

    File myFile = new File(Song.getFileInput()); 
    RandomAccessFile read = new RandomAccessFile(myFile, "rw"); 
    String readTitle = null, readArtist = null, readGenre = null; 
    Song so = null; 

    read.seek(0); 
    for(int i = 0; i < title.length(); i++){ 
     readTitle += read.readChar(); 
    } 

    read.seek(50); 
    for(int i = 0; i < artist.length(); i++){ 
     readArtist += read.readChar(); 
    } 

    read.seek(100); 
    for(int i = 0; i < genre.length(); i++){ 
     readGenre += read.readChar(); 
    } 

    so = new Song(readTitle, readArtist, readGenre); 
    read.close(); 
    return so; 
} 

如果我把它分配给一个名为“歌.dat“,它应该写入并读取该文件中的歌曲。在我退出程序并再次运行后,我再次创建名为“songs.dat”的文件。但是当我想要阅读和显示歌曲时,什么都不会发生。有没有人如何解决这个问题?

回答

0

RandomAccessFile.seek(long position)设置要读取或写入的文件位置。

当你开始阅读你的文件时,你使用read.seek(0)将位置设置为0。但是,从那里你不需要重新设置:

public Song readSong() throws FileNotFoundException, IOException { 

    File myFile = new File(Song.getFileInput()); 
    RandomAccessFile read = new RandomAccessFile(myFile, "rw"); 
    String readTitle = "", readArtist = "", readGenre = ""; 
    Song so = null; 

    read.seek(0); 
    for(int i = 0; i < title.length(); i++){ 
     readTitle += read.readChar(); 
    } 

    for(int i = 0; i < artist.length(); i++){ 
     readArtist += read.readChar(); 
    } 

    for(int i = 0; i < genre.length(); i++){ 
     readGenre += read.readChar(); 
    } 

    so = new Song(readTitle, readArtist, readGenre); 
    read.close(); 
    return so; 
} 

我也初始化字符串空字符串,所以你不要有“空”摆在首位,结果字符串

+0

这仍然没有解决问题。我仍然得到相同的输出。 – Foxwood211

+0

如果你确定你正在阅读你的readSong()和writeSong()函数,并且Song.getFileInput()是正确的。检查启动程序的用户对此文件(或实际创建它的目录)具有读/写权限 –