2012-02-26 108 views
1

我正在尋找一些幫助,我遇到了一些小問題。基本上我在我的應用程序中有一個「if else & else」語句,但我想添加另一個「if」語句來檢查文件,然後檢查該文件中的某一行文本。但我不確定如何做到這一點。if&else statements

  • 的「如果」檢查文件的「如果」檢查文件是否存在,但不包含在「其他」文本
  • 的某一行存在
  • 做點什麼

這裏是什麼ii

if(file.exists()) { 
         do this 
} else { 
         do this 
} 
+0

打開文件進行閱讀。如果它不存在,你會得到一個異常。然後,一旦文件打開,閱讀它,尋找線路。 或者,也可以從命令行grep它;-) – 2012-02-26 22:43:29

回答

2

除非我失去了一些東西,難道你只是使用else if

else if((file.exists())&&(!file.contains(Whatever))) { ... }

File.contains將需要實際檢查文件中的函數進行交換,但你的想法。

+0

否。如果該文件存在,她想做點什麼。 – 2012-02-26 22:42:26

+0

@TonyEnnis Bummer。我真的必須學會正確地閱讀這個問題,我將它理解爲「兩個文件都存在並且不包含XYZ,或者它存在幷包含它,否則......」,但是這樣做不會太有意義一個'else if'。嗯,看來,我真的需要睡一覺。 – malexmave 2012-02-26 22:45:39

5

這聽起來像你要麼需要:

if (file.exists() && readFileAndCheckForWhatever(file)) { 
    // File exists and contains the relevant word 
} else { 
    // File doesn't exist, or doesn't contain the relevant word 
} 

if (file.exists()) { 
    // Code elided: read the file... 
    if (contents.contains(...)) { 
     // File exists and contains the relevant word 
    } else { 
     // File exists but doesn't contain the relevant word 
    } 
} else { 
    // File doesn't exist 
} 

或逆轉前一個的邏輯來壓平

if (!file.exists()) { 
    // File doesn't exist 
} else if (readFileAndCheckForWhatever(file)) { 
    // File exists and contains the relevant word  
} else { 
    // File exists but doesn't contain the relevant word 
} 
+0

第二個看起來像我所需要的,但(contents.contains(...))拉動錯誤「內容無法解決」 – Leigh8347 2012-02-26 23:12:35

+0

@ Leigh8347:好的,你必須自己寫一些代碼。這就是「代碼省略」所涉及的內容 - 讀取文件。 – 2012-02-27 07:32:58

1

也許你的意思是這樣的:

if(file.exists() && containsLine(file)) 
{ 
    // do something 
} 
else 
{ 
    // do something else 
} 

public boolean containsLine(File f) 
{ 
    // do the checking here 
}