1 package net.sf.openrocket.util;
3 import java.io.BufferedOutputStream;
5 import java.io.FileOutputStream;
6 import java.io.FilterOutputStream;
7 import java.io.IOException;
8 import java.io.InterruptedIOException;
9 import java.io.OutputStream;
11 import javax.swing.SwingWorker;
13 import net.sf.openrocket.document.OpenRocketDocument;
14 import net.sf.openrocket.file.RocketSaver;
16 public class SaveFileWorker extends SwingWorker<Void, Void> {
18 private final OpenRocketDocument document;
19 private final File file;
20 private final RocketSaver saver;
22 public SaveFileWorker(OpenRocketDocument document, File file, RocketSaver saver) {
23 this.document = document;
30 protected Void doInBackground() throws Exception {
31 ProgressOutputStream os = new ProgressOutputStream(
32 new BufferedOutputStream(new FileOutputStream(file)),
33 (int)saver.estimateFileSize(document, document.getDefaultStorageOptions()));
36 saver.save(os, document);
40 } catch (Exception e) {
41 System.err.println("Error closing file: ");
49 private class ProgressOutputStream extends FilterOutputStream {
51 private final int totalBytes;
52 private int writtenBytes = 0;
53 private int progress = -1;
55 public ProgressOutputStream(OutputStream out, int estimate) {
57 this.totalBytes = estimate;
61 public void write(byte[] b, int off, int len) throws IOException {
62 out.write(b, off, len);
66 throw new InterruptedIOException("SaveFileWorker was cancelled");
71 public void write(byte[] b) throws IOException {
73 writtenBytes += b.length;
76 throw new InterruptedIOException("SaveFileWorker was cancelled");
81 public void write(int b) throws IOException {
86 throw new InterruptedIOException("SaveFileWorker was cancelled");
91 private void setProgress() {
92 int p = MathUtil.clamp(writtenBytes * 100 / totalBytes, 0, 100);
95 SaveFileWorker.this.setProgress(progress);