给出StringBuilder
这种形式:
data_driven: [data-driven, web economy, leading, Fortune 500, knowledge-driven, pyramid-based, market-driven, capital-based, profit-driven, market-focused, bottom-line focused, new economy, Brazilian, European ],
market_leaders: [market leaders, corporations, eCompanies, eBusinesses, web 2.0 corporations, virtual companies, virtual businesses, virtual eBusinesses, virtual eMonopolies, information workers ]
我需要在给定令牌(例如data_driven
或market_leaders
)后的括号内创建一个列表。
这是我的代码:
public List<String> getPhrases(StringBuilder fileContent, String token) {
StringReader reader = new StringReader(fileContent.toString());
BufferedReader br = new BufferedReader(reader);
StreamTokenizer tokenizer = new StreamTokenizer(br);
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // skip the ":"
tokenizer.nextToken(); // skip the "["
do {
tokenizer.nextToken(); // go to the first phrase
String stuff = tokenizer.sval;
list.add(stuff);
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
当我使用StringBuilder
和令牌作为参数调用方法时,我会在该行获得NullPointerException
:
if (tokenizer.sval.equals(token)) {
我已经打印出我的StringBuilder
并且 拥有我在调用方法时使用过的令牌。
有没有人知道为什么我会得到这个例外?
答案 0 :(得分:0)
我可能会对这个问题采取不同的方法,我会首先隔离外部令牌;然后我会隔离“[”和“]”的内容然后我会使用StringTokenizer
,即我会使用这种方法
// Static level, because it doesn't depend on outside state.
public static List<String> getPhrases(
StringBuilder fileContent, String token) {
// An output List.
List<String> al = new ArrayList<String>();
final int p1 = fileContent.indexOf(token);
if (p1 >= 0) { // we have a "token"
int pos1 = fileContent.indexOf("[", p1 + 1);
if (pos1 >= 0) { // we have an open "["
int pos2 = fileContent.indexOf("]", pos1 + 1);
if (pos2 >= 0) { // we have a closing "]"
String str = fileContent.substring(pos1 + 1,
pos2);
StringTokenizer st = new StringTokenizer(
str, ","); // Now use a Tokenizer.
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s != null) { // Don't trim a null!
al.add(s.trim());
} else { // You may not want this...
al.add("");
}
}
}
}
}
// Return that output List.
return al;
}