1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.jci.stores;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.commons.io.IOUtils;
30
31
32
33
34
35
36
37 public final class FileResourceStore implements ResourceStore {
38
39 private final File root;
40
41 public FileResourceStore( final File pFile ) {
42 root = pFile;
43 }
44
45 public byte[] read( final String pResourceName ) {
46 InputStream is = null;
47 try {
48 is = new FileInputStream(getFile(pResourceName));
49 final byte[] data = IOUtils.toByteArray(is);
50 return data;
51 } catch (Exception e) {
52 return null;
53 } finally {
54 IOUtils.closeQuietly(is);
55 }
56 }
57
58 public void write( final String pResourceName, final byte[] pData ) {
59 OutputStream os = null;
60 try {
61 final File file = getFile(pResourceName);
62 final File parent = file.getParentFile();
63 if (!parent.mkdirs() && !parent.isDirectory()) {
64 throw new IOException("could not create" + parent);
65 }
66 os = new FileOutputStream(file);
67 os.write(pData);
68 } catch (Exception e) {
69
70 } finally {
71 IOUtils.closeQuietly(os);
72 }
73 }
74
75 public void remove( final String pResourceName ) {
76 getFile(pResourceName).delete();
77 }
78
79 private File getFile( final String pResourceName ) {
80 final String fileName = pResourceName.replace('/', File.separatorChar);
81 return new File(root, fileName);
82 }
83
84
85
86
87 @Deprecated
88 public String[] list() {
89 final List<String> files = new ArrayList<String>();
90 list(root, files);
91 return files.toArray(new String[files.size()]);
92 }
93
94
95
96
97 @Deprecated
98 private void list(final File pFile, final List<String> pFiles) {
99 if (pFile.isDirectory()) {
100 final File[] directoryFiles = pFile.listFiles();
101 for (int i=0; i < directoryFiles.length; i++) {
102 list(directoryFiles[i], pFiles);
103 }
104 } else {
105 pFiles.add(pFile.getAbsolutePath().substring(root.getAbsolutePath().length()+1));
106 }
107 }
108
109 @Override
110 public String toString() {
111 return this.getClass().getName() + root.toString();
112 }
113
114 }