3838import java .nio .file .StandardOpenOption ;
3939import java .util .zip .GZIPInputStream ;
4040import java .util .zip .GZIPOutputStream ;
41+ import java .util .zip .ZipException ;
4142
4243import static java .nio .file .StandardCopyOption .REPLACE_EXISTING ;
4344
@@ -71,7 +72,7 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
7172 } else {
7273 this .tmpPath = Files .createTempFile (tmpDir , path .getFileName ().toString (),
7374 gzip ? ".tmp.gz" : ".tmp" );
74- outFile = Files .newOutputStream (tmpPath , StandardOpenOption . WRITE );
75+ outFile = Files .newOutputStream (tmpPath );
7576 }
7677
7778 OutputStream bufOut = new BufferedOutputStream (outFile );
@@ -86,7 +87,15 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
8687 inputStream = inputStream (new BufferedInputStream (Files .newInputStream (path )), gzip );
8788
8889 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+ }
9099 }
91100 }
92101
@@ -152,6 +161,25 @@ public Path getPath() {
152161 private static void copy (Path source , OutputStream sink , boolean gzip ) throws IOException {
153162 try (InputStream copyStream = inputStream (Files .newInputStream (source ), gzip )) {
154163 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 ;
155183 }
156184 }
157185
0 commit comments