无法在Java中的highscore表中插入行

无法在Java中的highscore表中插入行,java,insert,line,Java,Insert,Line,我是一名Java程序员初学者。我正在编写一个扫雷游戏,我想在我的高分表中插入一行。 每次,first essai都是成功的,但当我重播时,我无法插入一行,并且我有一个错误: 线程AWT-EventQueue-0 java.lang.IllegalStateException中出现异常:扫描程序已关闭 谁都能看出问题所在 public void insererLigne(String texte, int numLine, int numDelLine) { List<String

我是一名Java程序员初学者。我正在编写一个扫雷游戏,我想在我的高分表中插入一行。 每次,first essai都是成功的,但当我重播时,我无法插入一行,并且我有一个错误:

线程AWT-EventQueue-0 java.lang.IllegalStateException中出现异常:扫描程序已关闭

谁都能看出问题所在

public void insererLigne(String texte, int numLine, int numDelLine) {

    List<String> fileLines = new ArrayList<String>();

    try {

        for (int i = 1; scanner.hasNextLine(); i++) {       
            String line = scanner.nextLine();

            if (i == numLine) {
                fileLines.add(texte);
    }           
            if (i != numDelLine) {                   
                fileLines.add(line);
      }              
        }
    } 

    finally {     
        if (scanner != null) {                
            scanner.close();
       }            
    }

    PrintWriter pw = null;       
    try {          
        pw = new PrintWriter(fichier);       
        for (String line : fileLines) {        
            pw.println(line);              
        }           
    }  
    catch (FileNotFoundException e) {            
        e.printStackTrace();        
    } 

    finally {           
        if (pw != null) {            
            pw.close();           
        }          
    }       
}

根据注释,您应该做的是从对象/类本身中删除scanner成员字段,并在每次要读取方法体中的文件时创建一个新的scanner。结合使用try with resources的建议,您将得到如下结果:

try (Scanner scanner = new Scanner(fichier)) {
// use scanner here as before
}
catch(FileNotFoundException e) {
// do something sensible here...
// can probably ignore, no highscore file yet.
}
// no finally block needed, scanner cleaned up automatically
try (PrintWriter pw = new PrintWriter(fichier)) {
// use pw here as before.
}
catch(FileNotFoundException|IOException e) {
// do something sensible here. unable to write highscore file(!)
}
// no finally block needed, pw cleaned up automatically

编辑:作为补充说明,您应该知道您正在AWT事件调度GUI线程中执行阻塞IO操作。这通常不是一个好主意,因为这意味着您的GUI将被阻止,直到IO完成。出于类似的原因,未捕获异常也是GUI响应性的一个非常坏的预兆。因此,在GUI线程中执行IO对于学习/玩具程序来说是可以的,但是对于更健壮的程序,您应该考虑将读取/写入高分的工作委托给不同的线程。Swingworker或ExecutorService是个不错的选择。这个问题并不是Java特有的,它转化为许多常见UI工具包(如Qt或GTK)以及其他各种语言的基于事件循环的库的类似问题。

Scanner是一个类级变量,您将在finally块中关闭它,因此第二次它无法读取


解决方案:有两个选项,要么使用user268396建议的方法,要么不关闭finally块中的扫描仪,而是使用单独的方法,读取整个文件后应调用该方法

例外情况是,扫描器已关闭,请共享您声明和初始化扫描器对象的代码,并在您的帖子中重新格式化代码-我怀疑您的每一行代码之间并没有空行。。。我还强烈建议您使用try with resource语句,而不是手动关闭内容,每次处理异常只是转储堆栈跟踪并继续,就好像一切正常一样时,都要非常紧张……扫描器可能是一个成员字段,并且已关闭,因为此方法的第一次运行实际上会在finally{}块中关闭它@SaurabhJhunjhunwala{public class dataPersist{private static final String nomFichier=highscore.dat;private File fichier;private RandomAccessFile RandomAccessFile;private Scanner Scanner;…public void insererAlignetring texte,int numlinge,int numsuppligine}我应该删除我的final块吗?@user268396