38
38
import java .nio .file .StandardOpenOption ;
39
39
import java .util .zip .GZIPInputStream ;
40
40
import java .util .zip .GZIPOutputStream ;
41
+ import java .util .zip .ZipException ;
41
42
42
43
import static java .nio .file .StandardCopyOption .REPLACE_EXISTING ;
43
44
@@ -71,7 +72,7 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
71
72
} else {
72
73
this .tmpPath = Files .createTempFile (tmpDir , path .getFileName ().toString (),
73
74
gzip ? ".tmp.gz" : ".tmp" );
74
- outFile = Files .newOutputStream (tmpPath , StandardOpenOption . WRITE );
75
+ outFile = Files .newOutputStream (tmpPath );
75
76
}
76
77
77
78
OutputStream bufOut = new BufferedOutputStream (outFile );
@@ -86,7 +87,15 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
86
87
inputStream = inputStream (new BufferedInputStream (Files .newInputStream (path )), gzip );
87
88
88
89
if (tmpPath != null ) {
89
- copy (path , bufOut , gzip );
90
+ try {
91
+ copy (path , bufOut , gzip );
92
+ } catch (ZipException ex ) {
93
+ // restart output buffer
94
+ bufOut .close ();
95
+ // clear output file
96
+ outFile = Files .newOutputStream (tmpPath );
97
+ bufOut = new GZIPOutputStream (new BufferedOutputStream (outFile ));
98
+ }
90
99
}
91
100
}
92
101
@@ -152,6 +161,25 @@ public Path getPath() {
152
161
private static void copy (Path source , OutputStream sink , boolean gzip ) throws IOException {
153
162
try (InputStream copyStream = inputStream (Files .newInputStream (source ), gzip )) {
154
163
copy (copyStream , sink );
164
+ } catch (ZipException ex ) {
165
+ Path corruptPath = null ;
166
+ String suffix = "" ;
167
+ for (int i = 0 ; corruptPath == null && i < 100 ; i ++) {
168
+ Path path = source .resolveSibling (source .getFileName () + ".corrupted" + suffix );
169
+ if (!Files .exists (path )) {
170
+ corruptPath = path ;
171
+ }
172
+ suffix = "-" + i ;
173
+ }
174
+ if (corruptPath != null ) {
175
+ logger .error ("Original file {} was corrupted: {}."
176
+ + " Moved to {}." , source , ex , corruptPath );
177
+ Files .move (source , corruptPath );
178
+ } else {
179
+ logger .error ("Original file {} was corrupted: {}."
180
+ + " Too many corrupt backups stored, removing file." , source , ex );
181
+ }
182
+ throw ex ;
155
183
}
156
184
}
157
185
0 commit comments