-1

我需要编写一些代码来读取“已投票:”行的某个文件,然后检查它后面的数字。然后它需要获取这个数字,向其中添加一个,然后将其打印回文件中。这是我到目前为止所拥有的:

 try{
       File yourFile = new File(p + ".vote");
           if(!yourFile.exists()) {
               yourFile.createNewFile();
           } 
       FileOutputStream oFile = new FileOutputStream(yourFile, false); 
       this.logger.info("A vote file for the user " + p + " has been created!");
 } catch(Exception e) {
     this.logger.warning("Failed to create a vote file for the user " + p + "!");

那么,我该怎么做呢?

4

1 回答 1

1

您应该使用 Scanner 类来读取文件,我认为这对您来说会容易得多。

例子

File file = new File("k.vote");

try {
    Scanner scanner = new Scanner(file);
} catch(FileNotFoundException e) { 
    //handle this
}

//now read the file line by line...

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    String[] words = line.split(" ");
    //now loop through your words and see if you find voted: using the substring function
    for (int i = 0; i < words.length(); i++) {
        if (words[i].length() > 5) {
            String subStr = words[i].substring(0,5);
            if (subStr.compareTo("voted:") == 0) {
                //found what we are looking for
                String number = words[i].substring(6, words[i].length()-1);
            }
        }
    }
}

至于在文件中更新它的最有效方法 - 我会说保持你所在行数的计数器,直到你找到你试图改变的数字。然后打开一个要写入的文件,跳过x行,并像我们上面所做的那样解析字符串并更新变量。

于 2013-04-27T02:57:18.837 回答