为什么无法同时读取java文件中的对象和数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (102)

以下是我使用的代码:

 import java.io.*;
 import java.util.*;

 class writeobj implements Serializable
 {
   public String name;
   public long size;
 }

 class FileLists
 {
   public static void main(String[] args)  throws Exception
   {
   try{
    File folder = new File("/home/shubham/Desktop/packer/dem");

    File[] files = folder.listFiles();

    FileOutputStream fobj = new FileOutputStream("myfile.ser");

     ObjectOutputStream oobj = new ObjectOutputStream(fobj);
      int ch;

    for (File file : files) 
        {   
            if (file.isFile())
                {  
            writeobj obj = new writeobj();
                    obj.name = file.getName();
            obj.size = file.length();
            oobj.writeObject(obj);
            String str = file.getAbsolutePath();
            FileInputStream fre =new FileInputStream(str); 
            System.out.println(file.getName()+"-"+file.length()+"-"+str);


            //FileReader f = new FileReader(obj.name);
            byte[] buffer = new byte[1024];

            while((ch = fre.read(buffer))!=-1){
                //System.out.println((char)ch);
                fobj.write(buffer,0,ch);
            }
            //Fread = null;
            fre.close();
            obj = null;
        }
        }
}
catch(Exception e)
{
    System.out.println(e);
}       
}
}
import java.io.*; 
import java.util.*;

  class writeobj implements Serializable
  {
    public String name;
    public long size;
   }
  class FileLists
  {
   public static void main(String[] args) 
{

int ch;
//File folder = new File("/home/shubham/Desktop/packer/dem/hello/demo");
try
{
    FileInputStream fobj = new FileInputStream("myfile.ser");
    //BufferedInputStream br = new BufferedInputStream(fobj);

    ObjectInputStream ois = new ObjectInputStream(fobj);
    writeobj e;
    while( (e = (writeobj)ois.readObject()) != null)
    {
        FileWriter f = new FileWriter(e.name);

        System.out.println(e.name+"name :"+e.size);

        while((ch=ois.read())!= -1){
            System.out.println("as");
        }
    }   

}
catch(Exception ef){
System.out.println();
    ef.printStackTrace();
}

}
}

Stack Traces:

java.io.StreamCorruptedException: invalid type code: 69 at java.base/java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2937) at java.base/java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2971) at java.base/java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:3043) at java.base/java.io.ObjectInputStream.read(ObjectInputStream.java:906) at FileLists.main(createnewfile.java:33)

提问于
用户回答回答于

问题可能在于:

while((ch=ois.read())!= -1){
    System.out.println("as");
}

扫码关注云+社区

领取腾讯云代金券