gpt4 book ai didi

java - 将对象写入输出文本文件

转载 作者:行者123 更新时间:2023-12-01 09:55:52 25 4
gpt4 key购买 nike

我们正在测试一个java程序,我们想在其中直接写入对象,因此我们确实实现了以下测试文件,但不幸的是我们得到的文件包含未知字符,我们如何避免这个问题,我们还想写入另一个文件其中包含纯文本格式的对象及其属性,输出返回一个空文件..

 import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

public class AssignTest {

public static void main(String[] args) throws IOException {

FileOutputStream wo = new FileOutputStream("Assignment1.txt");//here we want the objects directly
ObjectOutputStream s = new ObjectOutputStream(wo);


FileWriter fw = new FileWriter("yami.txt");//while here we want the object with its attributes
PrintWriter pw = new PrintWriter(fw);


String fileName= "Assignment1.txt";
try{
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.add(new SalariedWorker());// index 0
SalariedWorker sw = (SalariedWorker) Worker1.get(0);//explicit casting
Worker1.add(new SalariedWorker(1000.0));// index 1
SalariedWorker sw1 = (SalariedWorker) Worker1.get(1);
Worker1.add(new HourlyWorker());// index 2
HourlyWorker hw = (HourlyWorker) Worker1.get(2);
Worker1.add(new HourlyWorker(100.0));// index 3
HourlyWorker hw1 = (HourlyWorker) Worker1.get(3);

Scanner prompt = new Scanner ( System.in);
System.out.println("Enter your monthly salary: ");
double monthlySalary = prompt.nextDouble();
sw.setSalary(monthlySalary);
System.out.println("Your monthly Salary is: " +monthlySalary+" AED");
System.out.println(sw.toString());

System.out.println("Enter the Percentage Increase for a Salaried worker: ");
double PercentIncreaseS = prompt.nextDouble();
sw.setpercentageIncrease(PercentIncreaseS);
sw.increasePayment(monthlySalary);
System.out.println(sw.toString(monthlySalary));

System.out.println("Enter your hourly rate: ");
double HourlyRate = prompt.nextDouble();
hw.setRate(HourlyRate);
System.out.println("Your Hourly Rate : "+HourlyRate+" AED");
System.out.println(sw.toString());

System.out.println("Enter the Percentage Increase for an Hourly worker: ");
double PercentIncreaseH = prompt.nextDouble();
hw.setpercentageIncrease(PercentIncreaseH);
hw.increasePayment(HourlyRate);
System.out.println(hw.toString(HourlyRate));

ObjectOutputStream os = new ObjectOutputStream ( new FileOutputStream(fileName));
os.close();

s.writeObject(sw);
s.writeObject(hw);


pw.print(sw);
pw.print(hw);

}
catch (ArithmeticException ax){
System.out.println(ax);
}
catch (IOException ex){
System.out.println(ex);
}
}
}

最佳答案

如果将对象序列化到文件中,则会在其中产生垃圾字符,因为它不是纯文本文件。如果您想要人类可读的文件,您可以使用 ObjectMapper 将对象转换为有意义的内容,例如 json 字符串,并将 json 字符串写入文件。

关于java - 将对象写入输出文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com