我对这件事有点问题。我试图在用户输入数据的地方创建一个数组,并且数据需要保存在 object.obj 文件中。
这是我的代码:
import java.util.*;
public class insertData implements java.io.Serializable
{
Scanner keyboard=new Scanner(System.in);
private String One;
private String Two;
public void new()
{
System.out.println("How many lines do you want to insert?");
int p=keyboard.nextInt();
for (int i = 0; i < p; i++)
{
One=keyboard.next();
Two=keyboard.next();
}
}
public String toString()
{
new();
String text=One+"\t"+Two;
return text;
}
}
File 类将是:
import java.io.*;
public class fileA
{
insertData iD = new insertData()
String a;
ObjectOutputStream oos;
ObjectInputStream ois;
public void writeFile(File file)
{
try
{
oos=new ObjectOutputStream(new FileOutputStream(file1));
a=iD.toString();
oos.writeObject(a);
oos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void readFile(File file1)
{
try
{
ois=new ObjectInputStream(new FileInputStream(file1));
String str=(String)ois.readObject();
System.out.println(str);
ois.close();
}
catch (IOException ex)
{
System.err.println(ex);
}
catch (ClassNotFoundException ex)
{
System.err.println(ex);
}
}
}
问题是这只保存输入的最后一行数据。结果应该是:
Text1 Text2
aaaaa bbbbb
ccccc ddddd