1 | package org.springframework.batch.item.util; |
2 | |
3 | import java.io.File; |
4 | import java.io.IOException; |
5 | |
6 | import org.springframework.batch.item.ItemStreamException; |
7 | import org.springframework.dao.DataAccessResourceFailureException; |
8 | import org.springframework.util.Assert; |
9 | |
10 | /** |
11 | * Utility methods for files used in batch processing. |
12 | * |
13 | * @author Peter Zozom |
14 | */ |
15 | public class FileUtils { |
16 | |
17 | // forbids instantiation |
18 | private FileUtils() {} |
19 | |
20 | /** |
21 | * Set up output file for batch processing. This method implements common logic for |
22 | * handling output files when starting or restarting job/step. |
23 | * When starting output file processing, method creates/overwrites new file. |
24 | * When restarting output file processing, method checks whether file is writable. |
25 | * |
26 | * @param file file to be set up |
27 | * @param restarted TRUE signalizes that we are restarting output file processing |
28 | * @param overwriteOutputFile If set to TRUE, output file will be overwritten |
29 | * (this flag is ignored when processing is restart) |
30 | * |
31 | * @throws IllegalArgumentException when file is NULL |
32 | * @throws IllegalStateException when staring output file processing, file exists and |
33 | * flag "shouldDeleteExisting" is set to FALSE |
34 | * @throws DataAccessResourceFailureException when unable to create file or file is not writable |
35 | */ |
36 | public static void setUpOutputFile(File file, boolean restarted, |
37 | boolean overwriteOutputFile) { |
38 | |
39 | Assert.notNull(file); |
40 | |
41 | try { |
42 | if (!restarted) { |
43 | if (file.exists()) { |
44 | if(!overwriteOutputFile){ |
45 | throw new ItemStreamException("File already exists: [" |
46 | + file.getAbsolutePath() + "]"); |
47 | } |
48 | file.delete(); |
49 | } |
50 | |
51 | if (file.getParent() != null ) { |
52 | new File(file.getParent()).mkdirs(); |
53 | } |
54 | file.createNewFile(); |
55 | Assert.state(file.exists(), "Output file must exist"); |
56 | } |
57 | } catch (IOException ioe) { |
58 | throw new ItemStreamException( |
59 | "Unable to create file: [" + file.getAbsolutePath() + "]", |
60 | ioe); |
61 | } |
62 | |
63 | if (!file.canWrite()) { |
64 | throw new ItemStreamException( |
65 | "File is not writable: [" + file.getAbsolutePath() + "]"); |
66 | } |
67 | } |
68 | } |