我正在读取一个文本文件,条件是忽略以 * 开头的单词。
example:
abc 1234 *text to be ignored
所以在这个例子中,我会在从文本文件读取时忽略“要忽略的文本”,并且只会将 abc 和 1234 存储在字符串数组中。
为此,我编写了以下代码。如何实现忽略以 * 开头的单词的条件?
public static void read(String filename) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader (new FileReader(filename));
while ((line = reader.readLine()) != null) {
String[] functionName = line.split("\\s+");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
startWith(String literal)
如果您的字符串以给定的字符串文字开头,则返回 true。
例如:
"1234".startsWith("12");
返回 true
。
所以你应该阅读所有单词并检查它是否以*开头甚至包含*,如果是,则忽略整个单词。
示例:
if(! word.startsWith("*")) {
// add to what ever you want
}
或
if(! word.contains("*")) {
// add to what ever you want
}
关于java - 从有条件的文本文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289836/