KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > inversoft > util > FileTools


1 /*
2  * Copyright (c) 2003, Inversoft
3  *
4  * This software is distribuable under the GNU Lesser General Public License.
5  * For more information visit gnu.org.
6  */

7 package com.inversoft.util;
8
9
10 import java.io.BufferedReader JavaDoc;
11 import java.io.BufferedWriter JavaDoc;
12 import java.io.File JavaDoc;
13 import java.io.FileReader JavaDoc;
14 import java.io.FileWriter JavaDoc;
15 import java.io.IOException JavaDoc;
16
17
18 /**
19  * This is a simple utility class that helps other class
20  * find files relative to the class path.
21  *
22  * @author Brian Pontarelli
23  * @since 1.0
24  * @version 2.0
25  */

26 public class FileTools {
27
28     /**
29      * Returns the system-dependent version of the given file or path. This is
30      * done by converting all the slash characters to the correct slash for the
31      * current operating system
32      *
33      * @param path The path to convert to the current operating system
34      * @return The converted path
35      */

36     public static String JavaDoc convertPath(String JavaDoc path) {
37
38         String JavaDoc newPath;
39         if (File.separatorChar == '\\') {
40             newPath = path.replace('/', '\\');
41         } else {
42             newPath = path.replace('\\', '/');
43         }
44
45         return newPath;
46     }
47
48     /**
49      * Copies the given from files contents to the given to file. This is done
50      * in 1024 byte chucks. If the to file exists and has content, it is deleted
51      * and replaced with the contents of the from file.
52      *
53      * @param from The from File
54      * @param to The to File
55      * @throws IOException If there was a problem during the copy
56      */

57     public static void copy(File JavaDoc from, File JavaDoc to) throws IOException JavaDoc {
58
59         // Delete the to file if it exists
60
if (to.exists()) {
61             to.delete();
62         }
63
64         FileReader JavaDoc reader = new FileReader JavaDoc(from);
65         BufferedReader JavaDoc br = new BufferedReader JavaDoc(reader);
66         FileWriter JavaDoc writer = new FileWriter JavaDoc(to);
67         BufferedWriter JavaDoc bw = new BufferedWriter JavaDoc(writer);
68
69         char [] buf = new char[1024];
70         int count = 0;
71         do {
72             count = br.read(buf, 0, 1024);
73             if (count != -1) {
74                 bw.write(buf, 0, count);
75             }
76         } while (count != -1 && count == 1024);
77
78         bw.close();
79         br.close();
80         writer.close();
81         reader.close();
82     }
83 }
Popular Tags