KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > file > FileUtil


1 package jodd.file;
2
3 import jodd.util.Util;
4
5 import java.io.BufferedInputStream;
6 import java.io.BufferedOutputStream;
7 import java.io.BufferedReader;
8 import java.io.BufferedWriter;
9 import java.io.File;
10 import java.io.FileInputStream;
11 import java.io.FileNotFoundException;
12 import java.io.FileOutputStream;
13 import java.io.FileReader;
14 import java.io.FileWriter;
15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import java.io.OutputStreamWriter;
20
21 /**
22  * File utilities.
23  */

24 public final class FileUtil {
25
26     // ---------------------------------------------------------------- misc utils
27

28     /**
29      * Returns current working folder string.
30      *
31      * @return current woking folder
32      */

33     public static String getWorkingDir() {
34         return System.getProperty("user.dir");
35     }
36
37     /**
38      * Returns current working folder.
39      *
40      * @return File for current woking folder
41      */

42     public static File getWorkingDirFile() {
43         return new File(System.getProperty("user.dir"));
44     }
45
46     /**
47      * Returns file size.
48      *
49      * @param fileName file name
50      *
51      * @return file size
52      */

53     public static long getFileSize(String fileName) {
54         return new File(fileName).length();
55     }
56
57     /**
58      * Returns file size.
59      *
60      * @param file file
61      *
62      * @return file size
63      */

64     public static long getFileSize(File file) {
65         return file.length();
66     }
67
68     /**
69      * Checks if two files are poiniting to the same file.
70      *
71      * @param file1 first file
72      * @param file2 second file
73      *
74      * @return true if files are pointing to the same file
75      */

76     public static boolean equals(String file1, String file2) {
77         return equals(new File(file1), new File(file2));
78     }
79     /**
80      * Checks if two files are poiniting to the same file.
81      *
82      * @param file1 first file
83      * @param file2 second file
84      *
85      * @return true if files are pointing to the same file
86      */

87     public static boolean equals(File file1, File file2) {
88         try {
89             file1 = file1.getCanonicalFile();
90             file2 = file2.getCanonicalFile();
91         } catch (IOException e) {
92             return false;
93         }
94         return file1.equals(file2);
95     }
96
97     /**
98      * Creates all folders.
99      *
100      * @param dirs dirs
101      *
102      * @return true if creating was successful, false otherwise
103      */

104     public static boolean mkdirs(String dirs) {
105         return new File(dirs).mkdirs();
106     }
107     /**
108      * Creates all folders.
109      *
110      * @param dirs dirs
111      *
112      * @return true if creating was successful, false otherwise
113      */

114     public static boolean mkdirs(File dirs) {
115         return dirs.mkdirs();
116     }
117
118     /**
119      * Creates a folder.
120      *
121      * @param dir dir
122      *
123      * @return true if creating was successful, false otherwise
124      */

125     public static boolean mkdir(String dir) {
126         return new File(dir).mkdir();
127     }
128     /**
129      * Creates a folders.
130      *
131      * @param dir dir
132      *
133      * @return true if creating was successful, false otherwise
134      */

135     public static boolean mkdir(File dir) {
136         return dir.mkdir();
137     }
138
139
140     // ---------------------------------------------------------------- file copy vairants
141

142     /**
143      * Buffer size (32KB) for file manipulation methods.
144      */

145     public static int FILE_BUFFER_SIZE = 32 * 1024;
146
147     /**
148      * Copies and overwrites a file to another file or folder.
149      *
150      * @param fileIn input file
151      * @param fileOut output file
152      *
153      * @return true if operation was successful, false otherwise
154      * @see #copy(File, File, int, boolean)
155      */

156     public static boolean copy(String fileIn, String fileOut) {
157         return copy(new File(fileIn), new File(fileOut), FILE_BUFFER_SIZE, true);
158     }
159     /**
160      * Copies a file to another file or folder.
161      *
162      * @param fileIn input file
163      * @param fileOut output file
164      *
165      * @return true if operation was successful, false otherwise
166      * @see #copy(File, File, int, boolean)
167      */

168     public static boolean copySafe(String fileIn, String fileOut) {
169         return copy(new File(fileIn), new File(fileOut), FILE_BUFFER_SIZE, false);
170     }
171
172     /**
173      * Copies and overwrites a file to another file or folder with specified buffer size.
174      *
175      * @param fileIn input file
176      * @param fileOut output file
177      * @param bufsize size of the buffer used for copying
178      *
179      * @return true if operation was successful, false otherwise
180      * @see #copy(File, File, int, boolean)
181      */

182     public static boolean copy(String fileIn, String fileOut, int bufsize) {
183         return copy(new File(fileIn), new File(fileOut), bufsize, true);
184     }
185     /**
186      * Copies a file to another file or folder with specified buffer size.
187      *
188      * @param fileIn input file
189      * @param fileOut output file
190      * @param bufsize size of the buffer used for copying
191      *
192      * @return true if operation was successful, false otherwise
193      * @see #copy(File, File, int, boolean)
194      */

195     public static boolean copySafe(String fileIn, String fileOut, int bufsize) {
196         return copy(new File(fileIn), new File(fileOut), bufsize, false);
197     }
198
199     /**
200      * Copies and overwrites a file to another file or folder.
201      *
202      * @param fileIn input file
203      * @param fileOut output file
204      *
205      * @return true if operation was successful, false otherwise
206      * @see #copy(File, File, int, boolean)
207      */

208     public static boolean copy(File fileIn, File fileOut) {
209         return copy(fileIn, fileOut, FILE_BUFFER_SIZE, true);
210     }
211     /**
212      * Copies a file to another file or folder.
213      *
214      * @param fileIn input file
215      * @param fileOut output file
216      *
217      * @return true if operation was successful, false otherwise
218      * @see #copy(File, File, int, boolean)
219      */

220     public static boolean copySafe(File fileIn, File fileOut) {
221         return copy(fileIn, fileOut, FILE_BUFFER_SIZE, false);
222     }
223
224     /**
225      * Copies and overwrites a file to another file or folder with specified buffer size.
226      *
227      * @param fileIn input file
228      * @param fileOut output file
229      * @param bufsize size of the buffer used for copying
230      *
231      * @return true if operation was successful, false otherwise
232      * @see #copy(File, File, int, boolean)
233      */

234     public static boolean copy(File fileIn, File fileOut, int bufsize) {
235         return copy(fileIn, fileOut, bufsize, true);
236     }
237     /**
238      * Copies a file to another file or folder with specified buffer size.
239      *
240      * @param fileIn input file
241      * @param fileOut output file
242      * @param bufsize size of the buffer used for copying
243      *
244      * @return true if operation was successful, false otherwise
245      * @see #copy(File, File, int, boolean)
246      */

247     public static boolean copySafe(File fileIn, File fileOut, int bufsize) {
248         return copy(fileIn, fileOut, bufsize, false);
249     }
250
251
252     // ---------------------------------------------------------------- file copy
253

254     /**
255      * Copies a file to another file or folder with specified buffer size and
256      * overwrite flag.
257      *
258      * @param fileIn input file
259      * @param fileOut output file
260      * @param bufsize size of the buffer used for copying
261      * @param overwrite should existing destination be overwritten
262      *
263      * @return true if operation was successful, false otherwise
264      * @see #copy(File, File, int, boolean)
265      */

266     public static boolean copy(String fileIn, String fileOut, int bufsize, boolean overwrite) {
267         return copy(new File(fileIn), new File(fileOut), bufsize, overwrite);
268     }
269
270     /**
271      * Copies a file to another file or folder with specified buffer size and
272      * overwrite flag. If source doesn't exist, operation fails. If source isn't
273      * file, operation fails. Destination may be a folder, in that case file will
274      * be copied in destination folder. If overwrite is on and source file points
275      * to the same file as edstination, operation is successful.
276      *
277      * @param fileIn input file
278      * @param fileOut output file
279      * @param bufsize size of the buffer used for copying
280      * @param overwrite should existing destination be overwritten
281      *
282      * @return true if operation was successful, false otherwise
283      */

284     public static boolean copy(File fileIn, File fileOut, int bufsize, boolean overwrite) /*throws IOException*/ {
285         // check if source exists
286
if (fileIn.exists() == false) {
287             return false;
288         }
289
290         // check if source is a file
291
if (fileIn.isFile() == false) {
292             return false;
293         }
294
295         // if destination is folder, make it to be a file.
296
if (fileOut.isDirectory() == true) {
297             fileOut = new File(fileOut.getPath() + File.separator + fileIn.getName());
298         }
299
300         if (overwrite == false) {
301             if (fileOut.exists() == true) {
302                 return false;
303             }
304         } else {
305             if (fileOut.exists()) { // if overwriting, check if destination is the same file as source
306
try {
307                     if (fileIn.getCanonicalFile().equals(fileOut.getCanonicalFile()) == true) {
308                         return true;
309                     }
310                 } catch (IOException ioex) {
311                     return false;
312                 }
313             }
314         }
315         return copyFile(fileIn, fileOut, bufsize);
316     }
317
318     // ---------------------------------------------------------------- copy file
319

320     /**
321      * Copies one file to another withut any checkings.
322      *
323      * @param fileIn source
324      * @param fileOut destination
325      *
326      * @return true if operation was successful, false otherwise
327      */

328     public static boolean copyFile(String fileIn, String fileOut) {
329         return copyFile(new File(fileIn), new File(fileOut), FILE_BUFFER_SIZE);
330     }
331     /**
332      * Copies one file to another withut any checkings.
333      *
334      * @param fileIn source
335      * @param fileOut destination
336      *
337      * @return true if operation was successful, false otherwise
338      */

339     public static boolean copyFile(File fileIn, File fileOut) {
340         return copyFile(fileIn, fileOut, FILE_BUFFER_SIZE);
341     }
342     /**
343      * Copies one file to another withut any checkings.
344      *
345      * @param fileIn source
346      * @param fileOut destination
347      * @param bufsize buffer size
348      *
349      * @return true if operation was successful, false otherwise
350      */

351     public static boolean copyFile(String fileIn, String fileOut, int bufsize) {
352         return copyFile(new File(fileIn), new File(fileOut), bufsize);
353     }
354
355     /**
356      * Copies one file to another withut any checkings.
357      *
358      * @param fileIn source
359      * @param fileOut destination
360      * @param bufsize buffer size
361      *
362      * @return true if operation was successful, false otherwise
363      */

364     public static boolean copyFile(File fileIn, File fileOut, int bufsize) {
365         FileInputStream in = null;
366         FileOutputStream out = null;
367         boolean result = false;
368         try {
369             in = new FileInputStream(fileIn);
370             out = new FileOutputStream(fileOut);
371             Util.copyPipe(in, out, bufsize);
372             result = true;
373         } catch(IOException ioex) {
374         } finally {
375             if (out != null) {
376                 try {
377                     out.close();
378                 } catch(IOException ioex) {
379                 }
380             }
381             if (in != null) {
382                 try {
383                     in.close();
384                 } catch(IOException ioex) {
385                 }
386             }
387         }
388         return result;
389     }
390
391     // ---------------------------------------------------------------- file move variants
392

393
394     public static boolean move(String fileNameIn, String fileNameOut) {
395         return move(new File(fileNameIn), new File(fileNameOut), true);
396     }
397     public static boolean moveSafe(String fileNameIn, String fileNameOut) {
398         return move(new File(fileNameIn), new File(fileNameOut), false);
399     }
400
401     public static boolean move(File fileIn, File fileOut) {
402         return move(fileIn, fileOut, true);
403     }
404     public static boolean moveSafe(File fileIn, File fileOut) {
405         return move(fileIn, fileOut, false);
406     }
407
408     // ---------------------------------------------------------------- file move
409

410     /**
411      * Moves one file to another file or folder with overwrite flag.
412      *
413      * @param fileNameIn
414      * @param fileNameOut
415      * @param overwrite overwrite flag
416      *
417      * @return true if successful, false otherwise
418      * @see #move(File, File, boolean)
419      */

420     public static boolean move(String fileNameIn, String fileNameOut, boolean overwrite) {
421         return move(new File(fileNameIn), new File(fileNameOut), overwrite);
422     }
423
424     /**
425      * Moves one file to another file or folder with overwrite flag. If source
426      * doesn't exist, oepration fails. If source is not file, oeration fails. If
427      * destionation is folder, file will be moved to a file with the same name in
428      * that folder.
429      *
430      * @param fileIn source
431      * @param fileOut destination
432      * @param overwrite overwrite flag
433      *
434      * @return true if successful, false otherwise
435      */

436     public static boolean move(File fileIn, File fileOut, boolean overwrite) {
437         // check if source exists
438
if (fileIn.exists() == false) {
439             return false;
440         }
441
442         // check if source is a file
443
if (fileIn.isFile() == false) {
444             return false;
445         }
446
447         // if destination is folder, make it to be a file.
448
if (fileOut.isDirectory() == true) {
449             fileOut = new File(fileOut.getPath() + File.separator + fileIn.getName());
450         }
451
452         if (overwrite == false) {
453             if (fileOut.exists() == true) {
454                 return false;
455             }
456         } else {
457             if (fileOut.exists()) { // if overwriting, check if destination is the same file as source
458
try {
459                     if (fileIn.getCanonicalFile().equals(fileOut.getCanonicalFile()) == true) {
460                         return true;
461                     } else {
462                         fileOut.delete(); // delete destination
463
}
464                 } catch (IOException ioex) {
465                     return false;
466                 }
467             }
468         }
469
470         return fileIn.renameTo(fileOut);
471     }
472
473     // ---------------------------------------------------------------- move file
474

475     /**
476      * Moves (renames) a file without any check.
477      *
478      * @param src source file
479      * @param dest destination file
480      *
481      * @return true if sucess, false otherwise
482      */

483     public static boolean moveFile(String src, String dest) {
484         return new File(src).renameTo(new File(dest));
485     }
486
487     /**
488      * Moves (renames) a file without any check.
489      *
490      * @param src source file
491      * @param dest destination file
492      *
493      * @return true if sucess, false otherwise
494      */

495     public static boolean moveFile(File src, File dest) {
496         return src.renameTo(dest);
497     }
498
499     // ---------------------------------------------------------------- move/copy directory
500

501     public static boolean moveDir(String fileIn, String fileOut) {
502         return moveDir(new File(fileIn), new File(fileOut));
503     }
504
505     /**
506      * Moves (renames) one folder to another. If source doesn't exist, operation
507      * fails. If source equals to destination, operaiton is successful. If source
508      * isn't a folder, operation fails. If destinatione exist, operation fails.
509      *
510      * @param fileIn source folder
511      * @param fileOut destination folder
512      *
513      * @return true if success, false otherwise
514      */

515     public static boolean moveDir(File fileIn, File fileOut) {
516         // check if source exists
517
if (fileIn.exists() == false) {
518             return false;
519         }
520
521         // check if source is a directory
522
if (fileIn.isDirectory() == false) {
523             return false;
524         }
525
526         // check if destination exists
527
if (fileOut.exists() == true) {
528             try {
529                 if (fileIn.getCanonicalFile().equals(fileOut.getCanonicalFile()) == true) {
530                     return true;
531                 } else {
532                     return false;
533                 }
534             } catch (IOException ioex) {
535                 return false;
536             }
537         }
538
539         return fileIn.renameTo(fileOut);
540     }
541
542
543     public static boolean copyDir(String srcDir, String dstDir) {
544         return copyDir(new File(srcDir), new File(dstDir));
545     }
546
547     /**
548      * Copies all files under source folder to destination. If destinatio does
549      * not exist, it will be created.
550      *
551      * @param srcDir source
552      * @param dstDir destination
553      *
554      * @return true if success, false otherwise
555      */

556     public static boolean copyDir(File srcDir, File dstDir) {
557         if (srcDir.isDirectory()) {
558             if (!dstDir.exists()) {
559                 dstDir.mkdir();
560             }
561             String[] files = srcDir.list();
562             for (int i = 0; i < files.length; i++) {
563                 if (copyDir(new File(srcDir, files[i]), new File(dstDir, files[i])) == false) {
564                     return false;
565                 }
566             }
567             return true;
568         }
569         return copyFile(srcDir, dstDir);
570     }
571
572
573     // ---------------------------------------------------------------- delete file/dir
574

575     /**
576      * Deletes files or empty folders, identical to File.delete().
577      *
578      * @param fileName name of file to delete
579      */

580     public static boolean delete(String fileName) {
581         return delete(new File(fileName));
582     }
583
584     /**
585      * Deletes files or empty folders, identical to File.delete().
586      *
587      * @param fileIn file to delete
588      */

589     public static boolean delete(File fileIn) {
590         return fileIn.delete();
591     }
592
593     /**
594      * Deletes files and/or complete tree recursively.
595      *
596      * @param pathName folder name to delete
597      */

598     public static boolean deleteDir(String pathName) {
599         return deleteDir(new File(pathName));
600     }
601
602     /**
603      * Deletes files and/or complete tree recursively. Returns true if all
604      * deletions were successful. If a deletion fails, the method stops
605      * attempting to delete and returns false.
606      *
607      * @param path folder to delete
608      *
609      * @return <code>true</code> if success, <code>false</code> otherwise
610      */

611     public static boolean deleteDir(File path) {
612         if (path.isDirectory()) {
613             File[] files = path.listFiles();
614             for (int i = 0; i < files.length; i++) {
615                 if (deleteDir(files[i]) == false) {
616                     return false;
617                 }
618             }
619         }
620         return path.delete();
621     }
622
623
624     // ---------------------------------------------------------------- string utilities
625

626     /**
627      * Buffer size (32KB) for file string methods.
628      */

629     public static int STRING_BUFFER_SIZE = 32 * 1024;
630
631     /**
632      * Reads file's content into a String. Implicitly assumes that the file is in
633      * the default encoding.
634      *
635      * @param fileName name of the file to read from
636      *
637      * @return string with file content or null
638      * @exception IOException
639      */

640     public static String readString(String fileName) throws IOException {
641         return readString(new File(fileName), STRING_BUFFER_SIZE);
642     }
643
644     /**
645      * Reads file's content into a String. Implicitly assumes that the file is in
646      * the default encoding.
647      *
648      * @param fileName name of the file to read from
649      * @param bufferSize buffer size
650      *
651      * @return string with file content or null
652      * @exception IOException
653      */

654     public static String readString(String fileName, int bufferSize) throws IOException {
655         return readString(new File(fileName), bufferSize);
656     }
657
658     /**
659      * Reads file's content into a String. Implicitly assumes that the file is in
660      * the default encoding.
661      *
662      * @param file file to read
663      *
664      * @return string with file content or null
665      * @exception IOException
666      */

667     public static String readString(File file) throws IOException {
668         return readString(file, STRING_BUFFER_SIZE);
669     }
670
671     /**
672      * Reads file's content into a String. Implicitly assumes that the file is in
673      * the default encoding.
674      *
675      * @param file file to read
676      * @param bufferSize buffer size
677      *
678      * @return string with file content or null
679      * @exception IOException
680      */

681     public static String readString(File file, int bufferSize) throws IOException {
682         long fileLen = file.length();
683         if (fileLen <= 0L) {
684             if (file.exists() == true) {
685                 return ""; // empty file
686
}
687             return null; // all other file len problems
688
}
689         if (fileLen > Integer.MAX_VALUE) { // max String size
690
throw new IOException("File too big for loading into a String!");
691         }
692
693         FileReader fr = null;
694         BufferedReader brin = null;
695         char[] buf = null;
696         try {
697             fr = new FileReader(file);
698             brin = new BufferedReader(fr, bufferSize);
699             int length = (int) fileLen;
700             buf = new char[length];
701             brin.read(buf, 0, length);
702         } finally {
703             if (brin != null) {
704                 brin.close();
705                 fr = null;
706             }
707             if (fr != null) {
708                 fr.close();
709             }
710         }
711         return new String(buf);
712     }
713
714     /**
715      * Writes string to a file. Implicitly assumes that the file will be written
716      * the default encoding.
717      *
718      * @param fileName name of the destination file
719      * @param s source string
720      *
721      * @exception IOException
722      */

723     public static void writeString(String fileName, String s) throws IOException {
724         writeString(new File(fileName), s, STRING_BUFFER_SIZE);
725     }
726
727     /**
728      * Writes string to a file. Implicitly assumes that the file will be written
729      * the default encoding.
730      *
731      * @param fileName name of the destination file
732      * @param s source string
733      * @param bufferSize buffer size
734      *
735      * @exception IOException
736      */

737     public static void writeString(String fileName, String s, int bufferSize) throws IOException {
738         writeString(new File(fileName), s, bufferSize);
739     }
740
741     /**
742      * Writes string to a file. Implicitly assumes that the file will be written
743      * the default encoding.
744      *
745      * @param file destination file
746      * @param s source string
747      *
748      * @exception IOException
749      */

750     public static void writeString(File file, String s) throws IOException {
751         writeString(file, s, STRING_BUFFER_SIZE);
752     }
753
754     /**
755      * Writes string to a file. Implicitly assumes that the file will be written
756      * the default encoding.
757      *
758      * @param file destination file
759      * @param s source string
760      * @param bufferSize buffer size
761      *
762      * @exception IOException
763      */

764     public static void writeString(File file, String s, int bufferSize) throws IOException {
765         FileWriter fw = null;
766         BufferedWriter out = null;
767         if (s == null) {
768             return;
769         }
770         try {
771             fw = new FileWriter(file);
772             out = new BufferedWriter(fw, bufferSize);
773             out.write(s);
774         } finally {
775             if (out != null) {
776                 out.close();
777                 fw = null;
778             }
779             if (fw != null) {
780                 fw.close();
781             }
782         }
783     }
784
785     // ---------------------------------------------------------------- unicode string utilities
786

787     /**
788      * Reads file's content into a String.
789      *
790      * @param fileName source file name
791      * @param encoding java encoding string
792      *
793      * @return string with file content or null
794      * @exception IOException
795      */

796     public static String readString(String fileName, String encoding) throws IOException {
797         return readString(new File(fileName), STRING_BUFFER_SIZE, encoding);
798     }
799
800     /**
801      * Reads file's content into a String.
802      *
803      * @param fileName source file name
804      * @param bufferSize buffer size
805      * @param encoding java encoding string
806      *
807      * @return string with file content or null
808      * @exception IOException
809      */

810     public static String readString(String fileName, int bufferSize, String encoding) throws IOException {
811         return readString(new File(fileName), bufferSize, encoding);
812     }
813
814     /**
815      * Reads file's content into a String.
816      *
817      * @param file source file
818      * @param encoding java encoding string
819      *
820      * @return string with file content or null
821      * @exception IOException
822      */

823     public static String readString(File file, String encoding) throws IOException {
824         return readString(file, STRING_BUFFER_SIZE, encoding);
825     }
826
827     /**
828      * Reads file's content into a String. This is a bit different implementation
829      * than other readString() method, since the number of characters in the file
830      * is not known. This currently only affest the value of the maximum file
831      * size.
832      *
833      * @param file source file
834      * @param bufferSize buffer size
835      * @param encoding java encoding string
836      *
837      * @return string with file content or null
838      * @exception IOException
839      */

840     public static String readString(File file, int bufferSize, String encoding) throws IOException {
841         long fileLen = file.length();
842         if (fileLen <= 0L) {
843             if (file.exists() == true) {
844                 return ""; // empty file
845
}
846             return null; // all other file len problems
847
}
848         if (fileLen > Integer.MAX_VALUE) { // max String size
849
throw new IOException("File too big for loading into a String!");
850         }
851
852         FileInputStream fis = null;
853         InputStreamReader isr = null;
854         BufferedReader brin = null;
855         
856         int length = (int) fileLen;
857         char[] buf = null;
858         int realSize = 0;
859         try {
860             fis = new FileInputStream(file);
861             isr = new InputStreamReader(fis, encoding);
862             brin = new BufferedReader(isr, bufferSize);
863             buf = new char[length]; // this is the weakest point, since real file size is not determined
864
int c; // anyhow, this is the fastest way doing this
865
while ((c = brin.read()) != -1) {
866                 buf[realSize] = (char) c;
867                 realSize++;
868             }
869         } finally {
870             if (brin != null) {
871                 brin.close();
872                 isr = null;
873                 fis = null;
874             }
875             if (isr != null) {
876                 isr.close();
877                 fis = null;
878             }
879             if (fis != null) {
880                 fis.close();
881             }
882         }
883         return new String(buf, 0, realSize);
884     }
885
886     /**
887      * Writes string to a file.
888      *
889      * @param fileName destination file name
890      * @param s source string
891      * @param encoding java encoding string
892      *
893      * @exception IOException
894      */

895     public static void writeString(String fileName, String s, String encoding) throws IOException {
896         writeString(new File(fileName), s, STRING_BUFFER_SIZE, encoding);
897     }
898
899     /**
900      * Writes string to a file.
901      *
902      * @param fileName destination file name
903      * @param s source string
904      * @param bufferSize buffer size
905      * @param encoding java encoding string
906      *
907      * @exception IOException
908      */

909     public static void writeString(String fileName, String s, int bufferSize, String encoding) throws IOException {
910         writeString(new File(fileName), s, bufferSize, encoding);
911     }
912
913     /**
914      * Writes string to a file.
915      *
916      * @param file destination file
917      * @param s source string
918      * @param encoding java encoding string
919      *
920      * @exception IOException
921      */

922     public static void writeString(File file, String s, String encoding) throws IOException {
923         writeString(file, s, STRING_BUFFER_SIZE, encoding);
924     }
925
926     /**
927      * Writes string to a file.
928      *
929      * @param file destination file
930      * @param s source string
931      * @param bufferSize buffer size
932      * @param encoding java encoding string
933      *
934      * @exception IOException
935      */

936     public static void writeString(File file, String s, int bufferSize, String encoding) throws IOException {
937         if (s == null) {
938             return;
939         }
940         FileOutputStream fos = null;
941         OutputStreamWriter osw = null;
942         BufferedWriter out = null;
943         try {
944             fos = new FileOutputStream(file);
945             osw = new OutputStreamWriter(fos, encoding);
946             out = new BufferedWriter(osw, bufferSize);
947             out.write(s);
948         } finally {
949             if (out != null) {
950                 out.close();
951                 osw = null;
952                 fos = null;
953             }
954             if (osw != null) {
955                 osw.close();
956                 fos = null;
957             }
958             if (fos != null) {
959                 fos.close();
960             }
961         }
962     }
963
964
965     // ---------------------------------------------------------------- object serialization
966

967     /**
968      * Buffer size (32KB) for object serialization methods.
969      */

970     public static int OBJECT_BUFFER_SIZE = 32 * 1024;
971
972     /**
973      * Writes serializable object to a file. Existing file will be overwritten.
974      *
975      * @param f name of the destination file
976      * @param o object to write
977      *
978      * @exception IOException
979      */

980     public static void writeObject(String f, Object o) throws IOException {
981         writeObject(f, o, OBJECT_BUFFER_SIZE);
982     }
983
984     /**
985      * Writes serializable object to a file with specified buffer size. Existing
986      * file will be overwritten.
987      *
988      * @param f name of the destination file
989      * @param o object to write
990      * @param bufferSize buffer size used for writing
991      *
992      * @exception IOException
993      */

994     public static void writeObject(String f, Object o, int bufferSize) throws IOException {
995         FileOutputStream fos = null;
996         BufferedOutputStream bos = null;
997         ObjectOutputStream oos = null;
998         try {
999             fos = new FileOutputStream(f);
1000            bos = new BufferedOutputStream(fos, bufferSize);
1001            oos = new ObjectOutputStream(bos);
1002            oos.writeObject(o);
1003        } finally {
1004            if (oos != null) {
1005                oos.close();
1006                bos = null;
1007                fos = null;
1008            }
1009            if (bos != null) {
1010                bos.close();
1011                fos = null;
1012            }
1013            if (fos != null) {
1014                fos.close();
1015            }
1016        }
1017    }
1018
1019
1020    /**
1021     * Reads seralized object from the file.
1022     *
1023     * @param f name of the source file
1024     *
1025     * @return serialized object from the file.
1026     * @exception IOException
1027     */

1028    public static Object readObject(String f) throws IOException, ClassNotFoundException, FileNotFoundException {
1029        return readObject(f, OBJECT_BUFFER_SIZE);
1030    }
1031
1032    /**
1033     * Reads seralized object from the file with specified buffer size
1034     *
1035     * @param f name of the source file
1036     * @param bufferSize size of buffer used for reading
1037     *
1038     * @return serialized object from the file.
1039     * @exception IOException
1040     * @exception ClassNotFoundException
1041     * @exception FileNotFoundException
1042     */

1043    public static Object readObject(String f, int bufferSize) throws IOException, ClassNotFoundException, FileNotFoundException {
1044        Object result = null;
1045        FileInputStream fis = null;
1046        BufferedInputStream bis = null;
1047        ObjectInputStream ois = null;
1048        try {
1049            fis = new FileInputStream(f);
1050            bis = new BufferedInputStream(fis, bufferSize);
1051            ois = new ObjectInputStream(bis);
1052            result = ois.readObject();
1053        } finally {
1054            if (ois != null) {
1055                ois.close();
1056                bis = null;
1057                fis = null;
1058            }
1059            if (bis != null) {
1060                bis.close();
1061                fis = null;
1062            }
1063            if (fis != null) {
1064                fis.close();
1065            }
1066        }
1067        return result;
1068    }
1069
1070    // ---------------------------------------------------------------- byte array
1071

1072
1073    /**
1074     * Reads file content as byte array.
1075     *
1076     * @param s file name
1077     *
1078     * @return file content
1079     * @exception IOException
1080     */

1081    public static final byte[] readBytes(String s) throws IOException {
1082        return readBytes(new File(s));
1083    }
1084
1085    /**
1086     * Reads file content as byte array.
1087     *
1088     * @param file file to read
1089     *
1090     * @return file content
1091     * @exception IOException
1092     */

1093    public static final byte[] readBytes(File file) throws IOException {
1094        FileInputStream fileinputstream = new FileInputStream(file);
1095        long l = file.length();
1096        if (l > Integer.MAX_VALUE) {
1097            throw new IOException("File too big for loading into a byte array!");
1098        }
1099        byte byteArray[] = new byte[(int)l];
1100        int i = 0;
1101        for (int j = 0; (i < byteArray.length) && (j = fileinputstream.read(byteArray, i, byteArray.length - i)) >= 0; i += j);
1102        if (i < byteArray.length) {
1103            throw new IOException("Could not completely read the file " + file.getName());
1104        }
1105        fileinputstream.close();
1106        return byteArray;
1107    }
1108
1109
1110
1111
1112    public static void writeBytes(String filename, byte[] source) throws IOException {
1113        if (source == null) {
1114            return;
1115        }
1116        writeBytes(new File(filename), source, 0, source.length);
1117    }
1118
1119    public static void writeBytes(File file, byte[] source) throws IOException {
1120        if (source == null) {
1121            return;
1122        }
1123        writeBytes(file, source, 0, source.length);
1124    }
1125
1126    
1127    public static void writeBytes(String filename, byte[] source, int offset, int len) throws IOException {
1128        writeBytes(new File(filename), source, offset, len);
1129    }
1130
1131    public static void writeBytes(File file, byte[] source, int offset, int len) throws IOException {
1132        if (len < 0) {
1133            throw new IOException("File size is negative!");
1134        }
1135        if (offset + len > source.length) {
1136            len = source.length - offset;
1137        }
1138        FileOutputStream fos = null;
1139        try {
1140            fos = new FileOutputStream(file);
1141            fos.write(source, offset, len);
1142        } finally {
1143            if (fos != null) {
1144                fos.close();
1145            }
1146        }
1147        return;
1148    }
1149
1150
1151}
1152
1153
1154
Popular Tags