首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileInputStream/DataInputStream

FileInputStream/DataInputStream
EN

Stack Overflow用户
提问于 2013-09-04 15:16:26
回答 1查看 4.4K关注 0票数 0

所以,我们有个任务要做一个猜谜游戏。程序必须生成一个数字,用户必须猜测。在用户猜对了之后,程序会显示“高分”(用户在猜对了之前要猜多少次)。

然后,我们应该将此高分保存在文本文件中,以便将其保存在计算机上,如果您重新启动计算机,它将不会丢失。我正在纠结的是程序应该如何读取我保存的文件。

这是我的“写代码”:

代码语言:javascript
复制
try {
    FileOutputStream write = new FileOutputStream 
    DataOutputStream out = new DataOutputStream(write);
    out.writeBytes(""+highscore);
    write.close();}
catch(IOException ioException ){
    System.err.println( "Could not write file" );
    return;}

很好,但我不知道怎么再读一遍。我的“阅读代码”:(我猜到了,我不知道这是否可行)

代码语言:javascript
复制
try{
    FileInputStream read = new FileInputStream
    DataInputStream in = new DataInputStream(read);
    in.readBytes(""+highscore);
    JOptionPane.showMessageDialog(null, "Your highscore is" + highscore);
catch(IOException ioException ){
    System.err.println( "Could not read file" );
    return;}

现在,我不知道in.readBytes(""+highscore);命令是否正确。我只是猜到了(我认为如果out.writeBytes(""+highscore);成功了,那么read也一定要工作)

如果readBytes是正确的命令,那么我将得到以下错误:

The method readBytes(String) is undefined for the type DataInputStream

我该怎么做?

一些信息:高分是和int。

EN

回答 1

Stack Overflow用户

发布于 2013-09-04 15:22:42

例如,如果highscoreint,则需要将int写入文件。你可以用

代码语言:javascript
复制
DataOutputStream out = new DataOutputStream(write);
out.writeInt(highscore);

然后用

代码语言:javascript
复制
DataInputStream in = new DataInputStream(read);
int highscore = in.readInt();

DataInputStream没有readBytes()。这就是为什么您的程序不编译。

DataIOStream类的全部目的是读写

底层的原始Java数据类型。以一种独立于机器的方式流动。

因此,使用与highscore的数据类型相对应的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18617657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档