Huxleye 2016-03-28 11:57 采纳率: 100%
浏览 3438
已采纳

java 关于将ArrayList存入文件与读取的问题

问题描述:这段代码是我未完成的主文件,本人java初学者,实在无法解决,渴求帮助。
这段程序是为了记录Task这个class并保存在timetracker.data中。程序首先要读取文件中的内容,我根据ObjectInputStream函数,想将文件内的内容的全部作为一个ArrayList整体读取出来,然后再在用户输入1时使用add()直接将新的Task添加到ArrayList中,最后在用户输入5的时候将这个ArrayList作为一个整体保存进去。以此来实现Task这个class的存取。 目前来看我的问题出在TaskList = (ArrayList)ois.readObject();这一行。
编译时会警报 未经检查的类型使用,找到java.lang.Object 需要java.util.ArrayList
我的疑问是 到底能不能通过readObject将文件内的所有内容读出,还是只能读出一个然后我的程序强行将这个Object转化成了ArrayList形式。
如果能,希望可以教我一下我写法的缺陷。
很抱歉浪费大家时间,感激不尽

import java.io.*;
import java.text.*;
import java.util.*;
import java.lang.*;

public class TimeTracker
{

public static void main(String[] args)  throws IOException
{
byte[] option = new byte[100];

ArrayList<Task> TaskList = new ArrayList<Task>();
for(;;){    //nihao

//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

ObjectInputStream ois = null;


try{
ois = new ObjectInputStream(new FileInputStream("timetracker.data"));
TaskList = (ArrayList<Task>)ois.readObject();

}  catch (ClassNotFoundException e){
    System.out.println("(None)");
} catch (EOFException e){       // catch EOF
System.out.println("have reached the end of file");
}   

finally{
    if( ois != null )
        {
        ois.close();
        }
int n = TaskList.size();
System.out.println(n);

    }

//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

ManuPrint manu = new ManuPrint();
manu.Print();

int numRead = System.in.read(option);
if((char) option[0] == '1'||(char) option[0] == '2'||(char) option[0] == '3'||(char) option[0] == '4'||(char) option[0] == '5'){
if((char) option[0] == '1'){
System.out.println("Enter new task (blank line ends input, no text ends the current task):");
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dt = new SimpleDateFormat("HH:mm");
//------------------------------record the last finished task

//------------------------------record the last finished task
// still not sloved multi lines
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
str=br.readLine();  
// multi lines

Task a = new Task((ft.format(date)),(dt.format(date)),"","",str);




TaskList.add(a);




}   // option 1

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
if((char) option[0] == '5'){
FileOutputStream fout = new FileOutputStream("timetracker.data");
ObjectOutputStream out = new ObjectOutputStream(fout);
try{

out.writeObject(TaskList);
out.flush();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
    out.close();
} catch(Exception e){
    e.printStackTrace();
    }
}

System.out.print("******SEEEEEE UUUUU NEEEXT TIMEEE*********");
    System.exit(0);
}   // option 5

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
} // if=1,2,3,4,5
else{
System.out.println("Invalid option!");
continue;
}
} //nihao
} // main
} //class

  • 写回答

2条回答

  • 毕小宝 博客专家认证 2016-03-28 13:06
    关注

    首先,分析下报错的这行代码,因为你既然使用的是readObject,那么你的文件timetracker.data中必须存的是通过java序列化的一个ArrayList对象,然后writeObject写到这个文件中的。
    所以,你的问题可能是这个文件中的东西并不是序列化的ArrayList类型的对象。你需要另写一个类线序列化一个对象向文件中存入标准的对象流,然后再执行你这段代码才行。
    我的简单测试案例:先写,再读。

     import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.ArrayList;
    
    public class SerialiTest {
        public static void main(String[] args) {
            SerialiTest serial = new SerialiTest();
            //先序列化对象写入文件
            serial.writeFirst();
            //再反序列化读取对象
            serial.readAfter();
        }
    
        public void writeFirst() {
            ArrayList<String> list = new ArrayList<String>();
            list.add("hello");
            list.add("world");
    
            FileOutputStream fout;
            ObjectOutputStream out = null;
            try {
                fout = new FileOutputStream("timetracker.data");
                out = new ObjectOutputStream(fout);
                out.writeObject(list);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
        public void readAfter() {
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new FileInputStream("timetracker.data"));
                ArrayList<String> list = (ArrayList<String>) ois.readObject();
                System.out.println(list);
            } catch (ClassNotFoundException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    
    

    你换成你使用的ArrayList就可以了。试试看。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿