【问题标题】:retain a value after running the program once?运行程序一次后保留一个值?
【发布时间】:2015-08-14 18:05:48
【问题描述】:

我正在制作一个程序,将歌曲的标题、艺术家和流派存储到数据文件中。像这样:

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

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

【问题讨论】:

    标签: java binaryfiles filereader random-access


    【解决方案1】:

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

    我还将您的字符串初始化为空字符串,因此您首先没有“空”字符串

    【讨论】:

    • 那仍然没有解决问题。我仍然得到相同的输出。
    • 如果你确定你正在通过你的 readSong() 和 writeSong() 函数并且 Song.getFileInput() 是正确的。检查启动您的程序的用户是否对该文件(或您实际创建它的目录)具有读/写权限
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多