-1

特定のファイルの「voted:」行を読み取り、その後の番号をチェックするコードを作成する必要があります。次に、この番号を取得し、それに 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 に答える