将流写入Java对象,然后使用它写入文件

时间:2019-03-18 06:10:30

标签: java stream inputstream

我的设计中包含以下架构:

一个类称为“ step1类”。在step1课程中,我接受文件上传。然后,稍后,调用者类将调用其他一些类,并且在这些步骤结束时,我想存储第一步中上传的文件。

代码如下:

public final class Caller{

    // Upload file page
    private FirstClassInfo firstClassInfo = new FirstClassInfo();

    // ... other private members and methods

    public void someMethodCallsThoseClasses(){

            new FirstClass(firstclassInfo);
            // other classes

    }

    public void allClassesCompleted(){
        // When all of the steps are completed, this will be executed

        // I would like to write uploaded file to the disk here
        File targetFile = new File(FirstClass.uploadLocation + firstclassInfo.getDiskName());

                    java.nio.file.Files.copy(
                            firstclassInfo.getStream(),
                            targetFile.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);

         // It gives me File upload exception: java.io.IOException: Stream Closed
    }
}

这是头等舱:

public class FirstClass {
    public static final String uploadLocation = "PATH TO FILE!";
    private FirstClassInfo firstclassInfo;
    private UploadFinishedHandler uploadFinishedHandler;

    public FirstClass (FirstClassInfo firstclassInfo){
        this.firstclassInfo= firstclassInfo;
    }

    // ... other methods


    // File upload method

    private void uploadFinish() {
        uploadFinishedHandler = (InputStream stream, String fileName, String mimeType, long length, int filesLeftInQueue) -> {
            // ... some methods
                firstclassInfo.setStream(stream);
            // ... some methods
        };
    }

}

这是FirstClassInfo:

public class FirstClassInfo{

    // ... other private members
    private String diskName;

    private InputStream stream;

    // getters and setters are below. Default getters and setters


}

我无法访问FirstClassInfo内部的流对象,因为一旦上传完成,流就关闭了。但是,我想使用allClassesCompleted方法访问数据并将其最后写入文件。我应该遵循的策略是什么?

0 个答案:

没有答案