2015-08-14 79 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()是正確的。檢查啓動程序的用戶對此文件(或實際創建它的目錄)具有讀/寫權限 –