if和else语句

Lei*_*347 1 java android if-statement

我正在寻找一些帮助我遇到的一个小问题.基本上我在我的应用程序中有一个"if&else"语句,但我想添加另一个"if"语句,检查文件,然后检查该文件中的某些文本行.但我不确定如何做到这一点.

  • on"if"检查文件是否存在
  • on"if"检查文件是否存在但是不包含某一行文本
  • 在"别的"做某事

这是我所拥有的

if(file.exists()) { 
                        do this
} else {
                        do this
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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
}
Run Code Online (Sandbox Code Playgroud)

要么

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
}
Run Code Online (Sandbox Code Playgroud)

或者颠倒前一个的逻辑来压扁它

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
}
Run Code Online (Sandbox Code Playgroud)