[英]How to read a Java String using BufferedReader's line.split method?
我想讀取一個文本文件,並將一些必需的值存儲為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];
}
}
您可能想要這樣的東西...
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.