2013-04-27 54 views
-1

我需要编写一些读取行“voted:”的特定文件的代码,然后检查它后面的数字。然后它需要取这个号码,加一个号码,然后打印回文件中。这是我到目前为止:读取一个文件,然后在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 + "!"); 

那么,我该怎么做呢?

+0

为什么你使用java的呢?可以使用unix脚本吗? – Lokesh 2013-04-27 02:44:32

+0

我为此使用Java,因为它是基于Java的服务器的插件。我也知道基本的Java。 – 2013-04-27 02:45:59

+0

感谢您的帮助!稍后会告诉你它是否工作。 – 2013-04-27 02:59:16

回答

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行数,并像上面那样解析字符串并更新变量。

+0

如果您有任何问题,请随时询问。我认为这个代码很自我解释。 – kamran619 2013-04-27 03:05:54

+1

它可能只是不清楚,但不能插入现有文件的中间文本,但解决方法是在读取文本时将文本写入第二个文件,删除旧文件并重命名新文件一个在它的位置 - 但我可能只是缺少一些东西 – MadProgrammer 2013-04-27 03:45:30

+0

我从来没有建议他应该在阅读时写作,但他完成后打开另一个文件。不过,你的建议确实更有效,因为他只需要经过一次文件。 – kamran619 2013-04-27 03:51:25

相关问题