我正在寻找一些帮助,我遇到了一些小问题。基本上我在我的应用程序中有一个“if else & else”语句,但我想添加另一个“if”语句来检查文件,然后检查该文件中的某一行文本。但我不确定如何做到这一点。if&else statements
- 的“如果”检查文件的“如果”检查文件是否存在,但不包含在“其他”文本
- 的某一行存在
- 做点什么
这里是什么ii
if(file.exists()) {
do this
} else {
do this
}
我正在寻找一些帮助,我遇到了一些小问题。基本上我在我的应用程序中有一个“if else & else”语句,但我想添加另一个“if”语句来检查文件,然后检查该文件中的某一行文本。但我不确定如何做到这一点。if&else statements
这里是什么ii
if(file.exists()) {
do this
} else {
do this
}
除非我失去了一些东西,难道你只是使用else if
?
else if((file.exists())&&(!file.contains(Whatever))) { ... }
File.contains
将需要实际检查文件中的函数进行交换,但你的想法。
否。如果该文件存在,她想做点什么。 – 2012-02-26 22:42:26
@TonyEnnis Bummer。我真的必须学会正确地阅读这个问题,我将它理解为“两个文件都存在并且不包含XYZ,或者它存在并包含它,否则......”,但是这样做不会太有意义一个'else if'。嗯,看来,我真的需要睡一觉。 – malexmave 2012-02-26 22:45:39
这听起来像你要么需要:
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
}
第二个看起来像我所需要的,但(contents.contains(...))拉动错误“内容无法解决” – Leigh8347 2012-02-26 23:12:35
@ Leigh8347:好的,你必须自己写一些代码。这就是“代码省略”所涉及的内容 - 读取文件。 – 2012-02-27 07:32:58
也许你的意思是这样的:
if(file.exists() && containsLine(file))
{
// do something
}
else
{
// do something else
}
public boolean containsLine(File f)
{
// do the checking here
}
打开文件进行阅读。如果它不存在,你会得到一个异常。然后,一旦文件打开,阅读它,寻找线路。 或者,也可以从命令行grep它;-) – 2012-02-26 22:43:29