KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > utils > FileUtils


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// FileUtils
15
// EV 19.12.2000
16
// MAP 24.01.2002 Files are stored into UTF-8 format.
17
//
18

19 package org.jahia.utils;
20
21 import java.io.BufferedInputStream JavaDoc;
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.BufferedReader JavaDoc;
24 import java.io.BufferedWriter JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import java.io.OutputStream JavaDoc;
32 import java.io.OutputStreamWriter JavaDoc;
33 import java.io.Reader JavaDoc;
34
35 import org.jahia.exceptions.JahiaException;
36
37 public class FileUtils {
38
39     private static org.apache.log4j.Logger logger =
40         org.apache.log4j.Logger.getLogger(FileUtils.class);
41
42     /***
43      * constructor
44      * EV 19.12.2000
45      *
46      */

47     private FileUtils () {
48         logger.debug("Starting fileUtils");
49     }
50
51     /***
52      * getInstance
53      * EV 19.12.2000
54      *
55      */

56     public static FileUtils getInstance () {
57         if (_fileUtils == null) {
58             _fileUtils = new FileUtils();
59         }
60         return _fileUtils;
61     }
62
63     /***
64      * EV 18.11.2000
65      * MAP 24.01.2002 : What's about these limitations ?
66      * FIXME : each jahia site should have its own file directory
67      * FIXME : no more than 100 files per directory
68      *
69      */

70     public String JavaDoc composeBigTextFullPathName (String JavaDoc jahiaDiskPath, int jahiaID,
71                                               int pageID, int fieldID, int versionID,
72                                               int versionStatus, String JavaDoc languageCode) {
73         return composeBigTextFullPathName(jahiaDiskPath,
74                                           composeBigTextFileNamePart(jahiaID, pageID, fieldID, versionID, versionStatus, languageCode));
75     }
76
77     public String JavaDoc composeBigTextFullPathName(String JavaDoc jahiaDiskPath, String JavaDoc bigTextFileNamePart) {
78         StringBuffer JavaDoc fileName = new StringBuffer JavaDoc();
79         fileName.append(jahiaDiskPath);
80         fileName.append(File.separator);
81         fileName.append(bigTextFileNamePart);
82         return fileName.toString();
83     }
84
85     public String JavaDoc composeBigTextFileNamePart (int jahiaID, int pageID,
86                                               int fieldID, int versionID,
87                                               int versionStatus,
88                                               String JavaDoc languageCode) {
89         StringBuffer JavaDoc fileName = new StringBuffer JavaDoc();
90         fileName.append(Integer.toString(jahiaID));
91         fileName.append("-");
92         fileName.append(Integer.toString(pageID));
93         fileName.append("-");
94         fileName.append(Integer.toString(fieldID));
95         fileName.append("-");
96         fileName.append(languageCode);
97         if (versionStatus > 1) {
98             fileName.append("-s");
99         } else if ( (versionID != 0) && (versionStatus <= 0)) {
100             fileName.append("-" + versionID);
101         }
102         fileName.append(".jahia");
103         return fileName.toString();
104     }
105
106     /***
107      * fileExists
108      * EV 18.11.2000
109      * called by loadContents
110      *
111      */

112     public boolean fileExists (String JavaDoc fileName)
113         throws JahiaException {
114         try {
115             File JavaDoc theFile = new File JavaDoc(fileName);
116             return theFile.exists();
117         } catch (SecurityException JavaDoc se) {
118             String JavaDoc errorMsg = "Security error in readFile : " + se.getMessage();
119             logger.error(errorMsg, se);
120             throw new JahiaException("Cannot access to jahia files",
121                                      errorMsg, JahiaException.FILE_ERROR,
122                                      JahiaException.CRITICAL_SEVERITY);
123         }
124     }
125
126     /**
127      * Read a text file in UTF-8 format.
128          * Avalaible from Jahia Edition 3. The old Jahia ASCII file are also readable
129      * but are saved in UTF-8 format.
130      *
131      * EV 18.11.2000
132      * MAP 31.01.2002 Try the UTF-8 format before the the ASCII format
133      *
134      * @param String fileName : the absolute path file name.
135      * @return : the String file _content.
136      */

137     public String JavaDoc readFile (String JavaDoc fileName)
138         throws JahiaException {
139         if (!tryToReadFile(fileName, UTF8)) {
140             logger.debug("Cannot read files in UTF-8 format trying ASCII");
141             if (!tryToReadFile(fileName, ASCII)) {
142                 logger.error("Cannot read files -> BAILING OUT");
143                 throw new JahiaException("Cannot access to jahia files",
144                                          "Error in readFile : " + fileName,
145                                          JahiaException.FILE_ERROR,
146                                          JahiaException.ERROR_SEVERITY);
147             }
148         }
149         return _content;
150     }
151
152     /**
153      * Read a text file in GBK or other format.
154      *
155      * Liu Gang 4.5.2003
156      *
157      * @param String fileName : the absolute path file name.
158      * @param String langCode.
159      * @return : the String file _content.
160      */

161     public String JavaDoc readFile (String JavaDoc fileName, String JavaDoc langCode)
162         throws JahiaException {
163         readFile(fileName);
164         return _content;
165     }
166
167     /**
168      * Write a String content to a UTF-8 file format.
169      *
170      * EV 18.11.2000
171      * MAP 24.01.2002 Write into UTF-8 file format
172      *
173      * @param String fileName : the absolute path file name.
174      * @param String fileContent : the String file content
175      */

176     public void writeFile (String JavaDoc fileName, String JavaDoc fileContent)
177         throws JahiaException {
178         try {
179             BufferedWriter JavaDoc out = new BufferedWriter JavaDoc(
180                 new OutputStreamWriter JavaDoc(
181                 new FileOutputStream JavaDoc(fileName), "UTF-8"));
182             out.write(fileContent);
183             out.close();
184         } catch (IOException JavaDoc ie) {
185             String JavaDoc errorMsg = "Error in writeFile : " + fileName +
186                               "\nIOException : " + ie.getMessage();
187             logger.error( errorMsg, ie);
188             throw new JahiaException("Cannot access to jahia files",
189                                      errorMsg, JahiaException.FILE_ERROR,
190                                      JahiaException.CRITICAL_SEVERITY);
191         }
192     }
193
194     /**
195      * Write a String content to a GBK or other file format.
196      *
197      * Liu Gang 4.5.2003
198      *
199      * @param String fileName : the absolute path file name.
200      * @param String langCode.
201      * @param String fileContent : the String file content
202      */

203     public void writeFile (String JavaDoc fileName, String JavaDoc fileContent, String JavaDoc langCode)
204         throws JahiaException {
205         writeFile(fileName, fileContent);
206     }
207
208     /***
209      * deleteFile
210      * EV 07.02.2001
211      *
212      */

213     public boolean deleteFile (String JavaDoc fileName) {
214         File JavaDoc theFile = new File JavaDoc(fileName);
215         return theFile.delete();
216     }
217
218     /**
219      * renames a file
220      * @param oldFileName name of the old file
221      * @param newFileName destination name
222      * @return true if it worked
223      */

224     public boolean renameFile (String JavaDoc oldFileName, String JavaDoc newFileName) {
225         File JavaDoc oldFile = new File JavaDoc(oldFileName);
226         File JavaDoc newFile = new File JavaDoc(newFileName);
227         return oldFile.renameTo(newFile);
228     }
229
230     // called by contentbigtextfield
231
/**
232      * copy a file
233      * @param oldFileName name of the old file
234      * @param newFileName destination name
235      * @return true if it worked
236      */

237     public boolean copyFile (String JavaDoc oldFileName, String JavaDoc newFileName) {
238         File JavaDoc oldFile = new File JavaDoc(oldFileName);
239         File JavaDoc newFile = new File JavaDoc(newFileName);
240         if (!oldFile.exists()) {
241             logger.error("Cannot copy file: source file doesn't exist");
242             return false;
243         }
244         if (oldFile.getAbsolutePath().equals(newFile.getAbsolutePath())) {
245             return true;
246         }
247         try {
248             copyStream(new FileInputStream JavaDoc(oldFile),
249                        new FileOutputStream JavaDoc(newFile));
250         } catch (IOException JavaDoc ioe) {
251             return false;
252         }
253         return true;
254     }
255
256     /***
257      * copyStream
258      * EV 30.11.2000
259      * called by download
260      *
261      */

262     public void copyStream (InputStream JavaDoc ins, OutputStream JavaDoc outs)
263         throws IOException JavaDoc {
264         int writeBufferSize = 4096;
265         byte[] writeBuffer = new byte[writeBufferSize];
266
267         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(ins, writeBufferSize);
268         BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc(outs,
269             writeBufferSize);
270         int bufread;
271         while ( (bufread = bis.read(writeBuffer)) != -1) {
272             bos.write(writeBuffer, 0, bufread);
273         }
274         bos.flush();
275         bos.close();
276         bis.close();
277     }
278
279     /**
280      * Return the content of a Reader as String
281      * @param reader
282      * @return
283      */

284     public static String JavaDoc readerToString(Reader JavaDoc reader) throws IOException JavaDoc{
285         if ( reader == null ){
286             return null;
287         }
288         StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
289         char[] stringToRead = new char[4096];
290         int count = -1;
291         while ( (count = reader.read(stringToRead, 0, 4096)) != -1) {
292             buff.append(stringToRead, 0, count);
293         }
294         return buff.toString();
295     }
296
297     /**
298      * Try to read a file in UTF-8 then GBK and finally ASCII, null if none
299      * of them success
300      *
301      * @param inputStream
302      * @return
303      */

304     public static String JavaDoc getFileCharset(InputStream JavaDoc inputStream){
305
306         BufferedReader JavaDoc in;
307         try {
308             in = new BufferedReader JavaDoc(
309                 new InputStreamReader JavaDoc(
310                 inputStream, "UTF-8"));
311             // success
312
return "UTF-8";
313         } catch (IOException JavaDoc ie) {
314         }
315         try {
316             in = new BufferedReader JavaDoc(
317                 new InputStreamReader JavaDoc(
318                 inputStream, "GBK"));
319             // success
320
return "GBK";
321         } catch (IOException JavaDoc ie) {
322         }
323         try {
324             in = new BufferedReader JavaDoc(
325                 new InputStreamReader JavaDoc(
326                 inputStream, "ASCII"));
327             // success
328
return "ASCII";
329         } catch (IOException JavaDoc ie) {
330         }
331         return null;
332     }
333
334     /**
335      * Try to read a file in an ASCII or UTF-8 format.
336      * MAP 31.1.2002
337      * @param String fileName : The absolute path file name
338      * @param int format : The file format supposing to read;
339                 1 = UTF-8, any value = ASCII
340      * @return True if success, false if not.
341      */

342     private boolean tryToReadFile (String JavaDoc fileName, byte format) {
343         try {
344             BufferedReader JavaDoc in;
345             if (format == GBK) {
346                 in = new BufferedReader JavaDoc(
347                     new InputStreamReader JavaDoc(
348                     new FileInputStream JavaDoc(fileName), "GBK"));
349             } else {
350                 if (format == UTF8) {
351                     in = new BufferedReader JavaDoc(
352                         new InputStreamReader JavaDoc(
353                         new FileInputStream JavaDoc(fileName), "UTF-8"));
354                 } else {
355                     in = new BufferedReader JavaDoc(
356                         new InputStreamReader JavaDoc(
357                         new FileInputStream JavaDoc(fileName)));
358                 }
359             }
360             _content = "";
361
362             StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
363             char[] stringToRead = new char[4096];
364             int count = -1;
365             while ( (count = in.read(stringToRead, 0, 4096)) != -1) {
366                 buff.append(stringToRead, 0, count);
367             }
368             _content = buff.toString();
369             buff = null;
370             /*
371                          char[] stringToRead = new char[4096];
372                          int count=-1;
373                          while ((count=in.read(stringToRead, 0, 4096)) != -1) {
374                 _content += new String(stringToRead, 0, count);
375                          }
376              */

377             in.close();
378             return true;
379         } catch (IOException JavaDoc ie) {
380             return false;
381         }
382     }
383
384     private final byte ASCII = 0;
385     private final byte UTF8 = 1;
386     private final byte GBK = 2;
387     private String JavaDoc _content;
388
389     private static FileUtils _fileUtils = null;
390 }
391
Popular Tags