[英]Split or parse a string in java
我有一个sample.txt文件,其内容为
12345#ABCDEF#12345#ADCDE
12345#ABCDEF#12345#ADCDE
FHJI
KLMN
OPQ
12345#ABCDEF#12345#ADCDE
现在我想基于#来分割/解析文件
我的输出应该是
Test1 : 12345
Test2 : ABCDEF
Test3 : 12345
Test4 : ADCDE
Test1 : 12345
Test2 : ABCDEF
Test3 : 12345
Test4 : ADCDE
FHJI
KLMN
OPQ
Test1 : 12345
Test2 : ABCDEF
Test3 : 12345
Test4 : ADCDE
我写如下
String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";
br = new BufferedReader(new FileReader("D:\\sample.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String line[] = sCurrentLine.split("#");
Test1 = line[0];
Test2 = line[1];
Test3 = line[2]
Test4 = line[3];
System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}
如果只有一行或sample.txt如下所示,则表示它正在工作
12345#ABCDEF#12345#ADCDE
12345#ABCDEF#12345#ADCDE
它不适用于已声明的最高示例。
请帮我。
谢谢。
这条线
String line[] = sCurrentLine.split("#");
将字符串拆分为n
片段,如果您解析的行中不存在#
,则会崩溃。 为了解决此问题,您有2个选择:
分配前检查数组的长度,以避免AIOOBE
while ((sCurrentLine = br.readLine()) != null) { String line[] = sCurrentLine.split("#"); Test1 = line[0]; Test2 = line.lenght > 1 ? line[1] : ""; Test2 = line.lenght > 2 ? line[2] : ""; Test2 = line.lenght > 3 ? line[3] : ""; System.out.println(Test1+"\\n"+Test2+"\\n"+Test3+"\\n"+Test4); }
您必须检查是否可以将字符串分割成所需的部分数量
String sCurrentLine;
String Test1 = "";
String Test2= "";
String Test3= "";
String Test4 = "";
br = new BufferedReader(new FileReader("D:\\sample.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String line[] = sCurrentLine.split("#");
if (line.length >= 4) {
Test1 = line[0];
Test2 = line[1];
Test3 = line[2]
Test4 = line[3];
} else {
Test4 = line[0] + "\n";
}
System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}
做这样的事情,以检查字符串中是否有足够的段。
String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";
br = new BufferedReader(new FileReader("D:\\sample.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String line[] = sCurrentLine.split("#");
if(line.length >= 4){
Test1 = line[0];
Test2 = line[1];
Test3 = line[2]
Test4 = line[3];
}
System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.