我如何 return 这个对象从文件中读入?
How can I return this object read in from a file?
所以我在这里尝试做的是从文件中加载一个 Customer 对象,但我不知道如何 return 方法中的对象。按照现在的代码,我收到一条错误消息,说 return type incompatible java.lang.object found needs Customer.
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
return x;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
我想我可以做这样的事情,但它也不起作用。
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
Customer y = new Customer(x);
return y;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//or do something like this:Customer x = new Customer(input.readObject)
我仍在 java 学习过程中,所以如果您发现任何其他错误,请告诉我。一如既往,我感谢大家花时间帮助我解决这个问题,期待有一天我有知识来回报并帮助他人。
尝试用 Customer x = (Customer) input.readObject();
替换 Object x = input.readObject();
所以我在这里尝试做的是从文件中加载一个 Customer 对象,但我不知道如何 return 方法中的对象。按照现在的代码,我收到一条错误消息,说 return type incompatible java.lang.object found needs Customer.
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
return x;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
我想我可以做这样的事情,但它也不起作用。
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
Customer y = new Customer(x);
return y;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//or do something like this:Customer x = new Customer(input.readObject)
我仍在 java 学习过程中,所以如果您发现任何其他错误,请告诉我。一如既往,我感谢大家花时间帮助我解决这个问题,期待有一天我有知识来回报并帮助他人。
尝试用 Customer x = (Customer) input.readObject();
Object x = input.readObject();