1 package com.bradmcevoy.io;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10
11
12
13
14
15
16
17
18
19
20 public class FileDeletingInputStream extends InputStream{
21
22 private static Logger log = LoggerFactory.getLogger(FileDeletingInputStream.class);
23
24 private File tempFile;
25 private InputStream wrapped;
26
27 public FileDeletingInputStream( File tempFile ) throws FileNotFoundException {
28 this.tempFile = tempFile;
29 wrapped = new FileInputStream( tempFile );
30 }
31
32 @Override
33 public int read() throws IOException {
34 return wrapped.read();
35 }
36
37 @Override
38 public int read( byte[] b ) throws IOException {
39 return wrapped.read( b );
40 }
41
42 @Override
43 public int read( byte[] b, int off, int len ) throws IOException {
44 return wrapped.read( b, off, len );
45 }
46
47 @Override
48 public synchronized void reset() throws IOException {
49 wrapped.reset();
50 }
51
52 @Override
53 public void close() throws IOException {
54 try{
55 wrapped.close();
56 } finally {
57 if(!tempFile.delete()) {
58 log.error("Failed to delete: " + tempFile.getAbsolutePath());
59 } else {
60 tempFile = null;
61 }
62 }
63 }
64
65 @Override
66 protected void finalize() throws Throwable {
67 if( tempFile != null && tempFile.exists() ) {
68 log.error("temporary file was not deleted. Was close called on the inputstream? Will attempt to delete: " + tempFile.getAbsolutePath());
69 if( !tempFile.delete()) {
70 log.error("Still couldnt delete temporary file: " + tempFile.getAbsolutePath());
71 }
72 }
73 super.finalize();
74 }
75
76
77 }