Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将对象附加到现有文件(泛型)?_Java_File_Object_Generics_Append - Fatal编程技术网

Java 如何将对象附加到现有文件(泛型)?

Java 如何将对象附加到现有文件(泛型)?,java,file,object,generics,append,Java,File,Object,Generics,Append,我在现有文件中追加泛型对象时遇到问题。如果参数为“true”,则该方法应将对象附加到现有文件,如果参数为“false”,则覆盖整个文件。“false”语句工作得非常好,它覆盖了整个文件,但我似乎无法让append语句工作。乍一看,它似乎什么都没做,但当我放置一个简单的系统.out.println(“test”);在while(true)循环中,它将永远运行。我怎样才能解决这个问题 public <T> void writeOneObject(T type, boolean appen

我在现有文件中追加泛型对象时遇到问题。如果参数为“true”,则该方法应将对象附加到现有文件,如果参数为“false”,则覆盖整个文件。“false”语句工作得非常好,它覆盖了整个文件,但我似乎无法让append语句工作。乍一看,它似乎什么都没做,但当我放置一个简单的系统.out.println(“test”);在while(true)循环中,它将永远运行。我怎样才能解决这个问题

public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{

    if (append == true){
        //TODO
        if (file.exists ()){
            ObjectOutputStream ois = null;
            try{
                ois = new ObjectOutputStream (new FileOutputStream (file, true));
                while (true){
                   ois.writeObject(type);
                }
            }catch (StreamCorruptedException e){
            }catch (EOFException e){

            }catch (Exception e){
                e.printStackTrace ();
            }finally{
                try{
                    if (ois != null) ois.close();
                }catch (StreamCorruptedException e){
                }catch (IOException e){
                    e.printStackTrace ();
                }
            }
        }


    }
    else {  //overwrites the entire file
        try {
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(type);
            oos.flush();
            oos.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }   catch (StreamCorruptedException e) {
            System.out.println("error");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

您必须使用某些条件来中断while循环,否则它将进入toss.Hmmm,
while(true){ois.writeObject(type);}
将运行,直到抛出某种异常为止。这几乎不可能是一个正确的条件。使用此循环,您试图实现什么?我认为您不需要循环,因为您只传递了一个要写入的对象。@任务即使在我删除while循环后,我写入的新对象在测试时也不会附加到现有文件中。
class NoHeaderObjectOutputStream extends ObjectOutputStream {
      public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
        super(os);
      }
      protected void writeStreamHeader() {}
    }