2013-04-27 25 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

相關問題