我有一个带有状态城市值的文本文件:-这些是文件中的内容:-
Madhya Pradesh-Bhopal
Goa-Bicholim
Andhra Pradesh-Guntur
我想分割州和城市...这是我的代码
FileInputStream fis= new FileInputStream("StateCityDetails.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int h=0;
String s;
String[] str=null;
byte[] b= new byte[1024];
while((h=bis.read(b))!=-1){
s= new String(b,0,h);
str= s.split("-");
}
for(int i=0; i<str.length;i++){
System.out.println(str[1]); ------> the value at 1 is Bhopal Goa
}
}
我在中央邦之间也有一个空格。。所以我想删除文件中各州之间的空格,并同时分割州和城市,并获得以下结果:-
str[0]----> MadhyaPradesh
str[1]----> Bhopal
str[2]-----> Goa
str[3]----->Bicholim
请帮助..提前谢谢您:)
我会在BufferedReader
这里使用a ,而不是您使用的方式。下面的代码段读取每一行,并以连字符(-
)分隔,并删除各部分中的所有空格。每个组件按从左到右(从上到下)的顺序输入到列表中。如果需要,列表会在最后转换为数组。
List<String> names = new ArrayList<String>();
BufferedReader br = null;
try {
String currLine;
br = new BufferedReader(new FileReader("StateCityDetails.txt"));
while ((currLine = br.readLine()) != null) {
String[] parts = currLine.split("-");
for (int i=0; i < parts.length; ++i) {
names.add(parts[i].replaceAll(" ", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// convert the List to an array of String (if you require it)
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
// print out result
for (String val : nameArr) {
System.out.println(val);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句