我在傳遞數組值給構造函數時遇到了一些問題。我有一個file.txt
,其中包含一些帶有值的行,例如:Java將值從數組傳遞到新的對象實例
peter | berlin | germany | 0930295235 | foo。
我想出瞭如何將行轉換爲數組。但我不知道如何將數組中的值傳遞給構造函數,以便將數組轉換爲具有數組屬性的對象。
這裏是主類:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileReader {
public static void main(String[] args) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("file.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read the file line by line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String s[] = strLine.split("\\|");
// System.out.println(java.util.Arrays.toString(s));
// System.out.println (strLine);
for (String element : s) {
System.out.println(element);
// HERE I NEED TO PASS THE ARRAY VALUES FOR EACH LINE TO TRANSFORM THE ARRAYS TO OBJECTS
Item item = new Item(element,element,element,element,element);
System.out.println("*************************************");
}
// Close the input stream
in.close();
} catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
這裏是類項目:
public class Item {
private String name;
private String city;
private String state;
private String number;
private String foo;
public Object(String name, String city, String state, String number,String foo){
this.name = name;
this.city = city;
this.state = state;
this.number = number;
this.foo = foo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
我需要的數據更多的工作對象。我感謝任何幫助。
選擇爲你的類一個更好的名字,描述它是什麼,不與已經存在 – codingbiz
你不應該調用類'Object'的一個混淆 - 這是一個Java超 –
什麼是錯誤? – codingbiz