我想读取一个文本文件并将一些必需的值存储为java字符串。
我使用Bufferedreader来读取和存储值。我插入了一行包含的行:可能的值为
NAME: lastname, firstname *CONTRACTOR*
NAME:
NAME: Sapi, Raj J.
NAME: Alle Peter, Shortley Swara
从上面我只需要姓氏和名字。有时这个价值根本不存在。在这种情况下,我如何验证名称行是否具有值?为此我使用下面的代码抛出Nullpointer异常。
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("CNUM")) {
cnum = line.split(" ")[1];
// break;
}
if (line.contains("NAME")) {
name = line.split(" ")[2];
}
}
答案 0 :(得分:2)
你可能想要这样的东西......
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("CNUM")) {
cnum = line.split(" ")[1];
// break;
}
if (line.trim().startsWith("NAME:")) {
line = line.replace("NAME:", "");
line = line.trim();
if (line.contains(",")){
String[] contractorName = line.split(",");
String lastName = contractorName[0].trim();
String firstName = contractorName[1].trim();
// use the last name and first name as you wish here.
} else {
// line doesn't contain a first and last name for contractor. invalid data.
continue;
}
}
}