读取文件然后在Java中执行操作

时间:2013-04-27 02:43:02

标签: java

我需要编写一些东西来读取“投票:”行的某个文件,然后检查它后面的数字。然后它需要取这个数字,添加一个,然后将其打印回文件。以下是我到目前为止的情况:

 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 + "!");

那么,我该怎么做?

1 个答案:

答案 0 :(得分: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 行数,并像上面那样解析字符串并更新变量。