package myio; import java.io.FileOutputStream import java.io.IOException; import java.io.ObjectOutputStream; public class Myobject { public static void main(String[] args) { // TODO Auto-generated method stub Book book=new Book("c语言","电子工业",50f ); try { ObjectOutputStream ostream=new ObjectOutputStream(new FileOutputstream("book.txt")); ostream.writeObject(book); ostream.close(); System.out.println("ok"); }catch(IOException e) { e.printStackTrace(); } }把这个代码补充完整 }
时间: 2024-03-02 15:52:05 浏览: 103
ChengFaBiao.zip_基础
这段代码中,Book类的代码没有给出,需要自己定义一个Book类,使得这段代码可以正常运行。补充完整后的代码如下:
```java
package myio;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Myobject {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book book = new Book("c语言", "电子工业", 50f);
try {
ObjectOutputStream ostream = new ObjectOutputStream(new FileOutputStream("book.txt"));
ostream.writeObject(book);
ostream.close();
System.out.println("ok");
} catch(IOException e) {
e.printStackTrace();
}
}
}
class Book implements java.io.Serializable {
private String title;
private String publisher;
private float price;
public Book(String title, String publisher, float price) {
this.title = title;
this.publisher = publisher;
this.price = price;
}
public String getTitle() {
return title;
}
public String getPublisher() {
return publisher;
}
public float getPrice() {
return price;
}
}
```
这段代码的作用是将一个Book对象序列化到文件book.txt中。需要注意的是,Book类需要实现Serializable接口才能被序列化。在Book类中定义了三个属性title、publisher、price,以及对应的getter方法。在Myobject类的main方法中,创建了一个Book对象book并将其序列化到文件中。
阅读全文