gpt4 book ai didi

java - 创建类的实例并导出到文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:41:19 26 4
gpt4 key购买 nike

如何创建一个类实例,然后将其导出到文件?希望你能帮忙。这是我的代码:

import java.io.*;

public class Testing {

public static void main(String[] args) {
// TODO Auto-generated method stub
Testing t = new Testing();

String fileName = ("C:/Users/Brandon/Desktop/Java/copy.java");

try {
FileWriter fileWriter =
new FileWriter(fileName);

BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

bufferedWriter.write(t);

bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");

我收到此错误消息:

The method write(int) in the type BufferedWriter is not applicable for the arguments (Testing).

如何解决这个问题?

最佳答案

这就是您的代码寻找该部分的方式:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Testing implements Serializable {

private static final long serialVersionUID = 1L;

public static void main(String args[]) {
Testing t = new Testing();
String fileName = new String("copy.ser");
t.write(t, fileName);
}

public void write(Testing t, String fileName) {

try {

FileOutputStream fout = new FileOutputStream("copy.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(t);
oos.close();
System.out.println("Done");

} catch (Exception ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
}
}
}

关于java - 创建类的实例并导出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900456/

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