我正在制作一个节目来存储歌曲'标题,艺术家和流派进入数据文件。像这样:
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;
}
如果我将它分配给名为&#34; songs.dat&#34;的文件,它应该写下并读取该文件中的歌曲。退出程序并再次运行后,我将文件命名为&#34; songs.dat&#34;再次。但是当我想阅读和显示歌曲时,没有任何反应。有人如何解决这个问题?
答案 0 :(得分: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;
}
我也将你的String初始化为空字符串,这样你就没有&#34; null&#34;结果首先是字符串