String Service;
BufferedReader in = null;
BufferedReader readn = new BufferedReader(new FileReader(new File(filepath)));
//Job [] dj = new Job[vlinenumber];
String linen="";
while ((linen = readn.readLine()) != null) {
//System.out.println (line);
String[] vem =linen.split(",");
int j=linen.length();
String regiration=vem[0];
String make=vem[1];
String Model=vem[2];
String Year=vem[3];
String odo=vem[4];
int ant=vem.length;
System.out.println(ant+"this is ");
String cv=vem[5];
if(ant==3){
String aaa= vem[6];
}
if(ant==4){
String aaa= vem[7];
}
Textfile示例:
OWNED,Ford,Falcon XL Ute,2008,167000,14331
FAST,Maserati,Quattroporte Sport GT,2007,48960,14321,90309
OK2BL8,Morris,Minor 1000,1969,567340,14315,90311
答案 0 :(得分:2)
你应该这样试试:
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader readn = new BufferedReader(new FileReader(new File(
"d:\\data.txt")));
String linen = "";
List<Details> dList = new ArrayList<>();
while ((linen = readn.readLine()) != null) {
String[] data = linen.split(",");
Details d = new Details();
if (data.length > 0) {
d.setReg(data[0]);
}
if (data.length > 1) {
d.setMake(data[1]);
}
if (data.length > 2) {
d.setModel(data[2]);
}
if (data.length > 3) {
d.setYear(data[3]);
}
if (data.length > 4) {
d.setOdo(data[4]);
}
if (data.length > 5) {
d.setCv(data[5]);
}
if (data.length > 6) {
d.setAa(data[6]);
}
if (data.length > 7) {
d.setAa(data[7]);
}
System.out.println(d);
dList.add(d);
}
}
}
模特课:
class Details {
String reg;
String make;
String model;
String year;
String odo;
String aa;
String cv;
public String getReg() {
return reg;
}
public void setReg(String reg) {
this.reg = reg;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getOdo() {
return odo;
}
public void setOdo(String odo) {
this.odo = odo;
}
public String getAa() {
return aa;
}
public void setAa(String aa) {
this.aa = aa;
}
public String getCv() {
return cv;
}
public void setCv(String cv) {
this.cv = cv;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return reg + "\t" + make + "\t" + model + "\t" + year + "\t" + odo+"\t"+cv+"\t"+aa;
}
}
答案 1 :(得分:1)
这样的事情可以解决问题,但你应该考虑使用更复杂的结构(实体类):
String fileContent = "OWNED,Ford,Falcon XL Ute,2008,167000,14331\nFAST,Maserati,Quattroporte Sport GT,2007,48960,14321,90309\nOK2BL8,Morris,Minor 1000,1969,567340,14315,90311";
String[] rows = fileContent.split("\n");
String data[][] = new String[rows.length][];
for (int i = 0; i < rows.length; i++) {
String row = rows[i];
data[i] = row.split(",");
}
此代码将创建包含文件内容的二维数组。对于此数据,它应如下所示:
data[0][0] -> "OWNED"
data[0][1] -> "Ford"
[...]
data[1][0] -> "FAST"
据我所知,包含值的数组(2d)可以具有可变长度对您来说很重要。这适用于这种方法。