vio*_*iwi 3 java file-io serialization
我想在TXT文件中以人类可读的形式编写对象,该文件将保存为具有不需要的字符的普通序列化对象.
请建议我如何重写相同的程序以保存到人类可读的TXT文件中
import java.io.*;
class book implements Serializable
{
String name;
String author;
int nop;
int price;
int discount;
void getDiscount()
{
int finalprice=price-((price/discount));
System.out.println("Final price after discount="+finalprice);
}
public String toString()
{
return name+author+nop+price+discount;
}
}
class fileio
{
public static void main(String args[])
{
MainClass mainObject=new MainClass();
mainObject.writeToFile();
book javabook=new book();
javabook.name="Java unleashed";
javabook.author="someone";
javabook.nop=1032;
javabook.price=450;
javabook.discount=10;
javabook.getDiscount();
}
public void writeToFile()
{
try
{
File file=new File("JavaBook1.txt");
FileWriter fw=new FileWriter(file.getAbsoluteFile());
BufferedWriter bw=new BufferedWriter(fw);
bw.write(book.toString());
bw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
看看下面是否解决了你的目的
覆盖Object类的toString()方法以返回对象的状态,然后使用文件编写器将其输出写入文本文件
如果你想要xml类型的表示,请选择JAXB方法
更新: -
请忽略下面程序中的语法/编译错误,因为我还没有测试过,但它会给你一个简短的想法
class book implements Serializable
{
String name;
String author;
int nop;
int price;
int discount;
void getDiscount()
{
int finalprice=price-((price/discount));
System.out.println("Final price after discount="+finalprice);
}
public String toString() {
return name + author +nop + price +discount;
// above can be any format whatever way you want
}
}
Run Code Online (Sandbox Code Playgroud)
现在在你的主要课堂上
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
class fileio
{
public static void main(String args[])
{
fileio mainObject=new fileio();
book javabook=new book();
javabook.name="Java unleashed";
javabook.author="someone";
javabook.nop=1032;
javabook.price=450;
javabook.discount=10;
javabook.getDiscount();
mainObject.writeToFile(javabook);
}
public void writeToFile(book javabook)
{
try
{
File file=new File("JavaBook1.txt");
FileWriter fw=new FileWriter(file.getAbsoluteFile());
BufferedWriter bw=new BufferedWriter(fw);
bw.write(javabook.toString());
bw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)