【问题标题】:My program isn't reading the file as it's supposed to be我的程序没有像预期的那样读取文件
【发布时间】:2011-04-30 18:33:40
【问题描述】:

我正在尝试创建一个 int 值,它每秒增加一个计数器,然后当你关闭程序时,它会将值保存到 .txt 文件中,然后,它应该,当你再次启动程序,从文件中读取 int 值,然后再次从该值继续,但是,它正在正确保存,它会生成文件,但是当我再次启动程序时,它将再次从 1 开始,并且不是保存在 .txt 文件中的值。

int值:

    public int points;

getter 和 setter,位于 MrStan.class 中

    public int getPoints(){
    return points;
}

public void setPoints( int points ){
    this.points = points;
}

我是如何读取文件的:

        MrStanReadFile r = new MrStanReadFile();
    r.openFile();
    r.readFile();
    r.closeFile();

我的 ReadFile 类:

public class MrStanReadFile {

private Scanner x;
MrStan a = new MrStan();

public void openFile(){
    try{
        x = new Scanner(new File("D:/MrStan/text.txt"));
    }catch(Exception ex){
        System.out.println("COULD NOT FIND TEXT.TXT");
    }
}

public void readFile(){
    while(x.hasNext()){
        String p = x.next();
        int pointset = Integer.parseInt(p);
        a.setPoints(pointset);
    }
}

public void closeFile(){
    x.close();
}

}

其他使用int的地方:

待办事项:

    public MrStan(){
    timer.schedule(new todoTask(), 0, 1 * 1000);
}

class todoTask extends TimerTask{
    public void run(){  
        points++;
        repaint();
    }
}

private Timer timer = new Timer();

        g.drawString("Points: " + points, 75, 83);

好的,在 readFile 方法中,您将看到一个字符串 p,即文本文件中的字符串。我使用 Integer.parseInt() 将字符串转换为 int,然后,我将我的 int 值设置为转换后的点集值,但它没有改变,我的程序将如何工作,所以它将从设置的数字开始.txt 文件?

【问题讨论】:

  • 如果您还发布 MrStan.setPoints 的代码和使用该整数的代码应该会很棒。设置值或使用它一定有一些错误......
  • “但它没有改变”。什么没有改变?点集中的值?你能缩小你的问题范围吗?
  • 程序开始的int,应该从文件中的int值开始
  • 问题不在你发布的代码中。

标签: java file java.util.scanner


【解决方案1】:
  1. 您是否检查了输出 "COULD NOT FIND TEXT.TXT"
  2. int pointset = Integer.parseInt(p); 之后添加System.out.println("Read: "+ pointset);
  3. 确保您在其他任何地方都没有 this.points = 0;
  4. 您在MrStanReadFile 中定义MrStan a = new MrStan();。您确定它与您在class todoTask 中使用的对象相同吗?

【讨论】:

  • 1.没有输出。 2. 将文件变红,并打印文件中的内容。 3. 我不知道, 4. 我不确定,但我需要使用来自 MrStan.class 的方法。 getPoints 似乎有效,但 setPoints 无效。
  • @Stan 发布完整的 todoTask 类
猜你喜欢
  • 2016-06-19
  • 2013-04-11
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多