KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gcc > util > FileUtil


1 /*
2  * Copyright 2004 The Apache Software Foundation or its licensors, as
3  * applicable.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14  * implied.
15  *
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19 package gcc.util;
20
21 import gcc.*;
22 import gcc.properties.*;
23 import java.io.*;
24 import java.util.*;
25
26 public abstract class FileUtil
27 {
28     // private data
29

30     private static int _tempIndex;
31
32     private static Object _tempIndexLock = new Object();
33
34     // public methods
35

36     public static int compareLines(String file1, String file2)
37     {
38         return compareLines(file1, file2, false);
39     }
40
41     public static int compareLines(String file1, String file2, boolean removeTopLevelComments)
42     {
43         String lines1 = readLines(file1, removeTopLevelComments);
44         String lines2 = readLines(file2, removeTopLevelComments);
45         return lines1.compareTo(lines2);
46     }
47
48     public static void copyDir(String fromDir, String toDir)
49     {
50         copyDir(fromDir, toDir, true);
51     }
52
53     public static void copyDir(String fromDir, String toDir, boolean rec)
54     {
55         File dirFile = new File(fromDir);
56         if(!dirFile.exists())
57         {
58             return;
59         }
60
61         File toDirFile = new File(toDir);
62         if (! toDirFile.exists())
63         {
64             toDirFile.mkdir();
65         }
66         String[] fileList = dirFile.list();
67         if (fileList != null)
68         {
69             for (int i = 0; i < fileList.length; i++)
70             {
71                 String name = fileList[i];
72                 String from = fromDir + File.separator + name;
73                 String to = toDir + File.separatorChar + name;
74                 File file = new File(from);
75                 if (file.isDirectory())
76                 {
77                     if (rec)
78                     {
79                         copyDir(from, to);
80                     }
81                 }
82                 else
83                 {
84                     copyFile(from, to);
85                 }
86             }
87         }
88     }
89
90     public static void copyFile(String from, String to)
91     {
92         mkdirs(to);
93         try
94         {
95             InputStream input = new BufferedInputStream(new FileInputStream(from));
96             OutputStream output = new BufferedOutputStream(new FileOutputStream(to));
97             int c;
98             while ((c = input.read()) != -1)
99             {
100                 output.write(c);
101             }
102             input.close();
103             output.close();
104         }
105         catch (IOException ex)
106         {
107             throw new SystemException(ex);
108         }
109     }
110
111     public static void copyFiles(String fromDir, String toDir, List files)
112     {
113         for (Iterator i = files.iterator(); i.hasNext();)
114         {
115             String file = (String)i.next();
116             copyFile(fromDir + "/" + file, toDir + "/" + file);
117         }
118     }
119
120     public static void deleteDir(String dir)
121     {
122         File dirFile = new File(dir);
123         if (dirFile.exists())
124         {
125             deleteFilesInDir(dir);
126             dirFile.delete();
127         }
128     }
129
130     public static void deleteFile(String file)
131     {
132         new File(file).delete();
133     }
134
135     public static void deleteFiles(List files)
136     {
137         for (Iterator i = files.iterator(); i.hasNext();)
138         {
139             String fileName = (String)i.next();
140             File file = new File(fileName);
141             file.delete();
142         }
143     }
144
145     public static void deleteFilesInDir(String dir)
146     {
147         File dirFile = new File(dir);
148         String[] fileList = dirFile.list();
149         if (fileList != null)
150         {
151             for (int i = 0; i < fileList.length; i++)
152             {
153                 String path = dir + File.separator + fileList[i];
154                 File file = new File(path);
155                 if (file.isDirectory())
156                 {
157                     deleteDir(path);
158                 }
159                 file.delete();
160             }
161         }
162     }
163
164     public static String expandHomeRelativePath(String path)
165     {
166         if (path.startsWith("~"))
167         {
168             path = SystemProperties.getHome() + path.substring(1);
169         }
170         return path;
171     }
172
173     public static List findFiles(String baseDir)
174     {
175         return findFiles(baseDir, "", true, true, "");
176     }
177
178     public static List findFiles(String baseDir, String pattern)
179     {
180         return findFiles(baseDir, pattern, true, true, "");
181     }
182
183     public static List findFiles(String baseDir, String pattern, boolean fullPath, boolean recursive)
184     {
185         return findFiles(baseDir, pattern, fullPath, recursive, "");
186     }
187
188     private static List findFiles(String baseDir, String pattern, boolean fullPath, boolean recursive, String relativeBase)
189     {
190         if (pattern.equals("**"))
191         {
192             pattern = ""; // Equivalent to "*"
193
recursive = true;
194         }
195         final String prefix = StringUtil.beforeFirst("*", pattern);
196         final String suffix = StringUtil.afterFirst("*", pattern);
197         final boolean finalRecursive = recursive;
198         FilenameFilter filter = new FilenameFilter()
199         {
200             public boolean accept(File file, String name)
201             {
202                 if (finalRecursive && new File(file.getPath() + File.separator + name).isDirectory())
203                 {
204                     return true;
205                 }
206                 return name.startsWith(prefix) && name.endsWith(suffix);
207             }
208         }
209         ;
210         List list = new LinkedList();
211         File dirFile = new File(baseDir);
212         String[] files = dirFile.list(filter);
213         if (files != null)
214         {
215             int n = files.length;
216             for (int i = 0; i < n; i++)
217             {
218                 String fileName = files[i];
219                 String fullName = baseDir.length() == 0 ? fileName
220                     : (baseDir + (fullPath ? File.separatorChar : '/') + fileName);
221                 File file = new File(fullName);
222                 if (file.isDirectory())
223                 {
224                     if (recursive)
225                     {
226                         String relativeName = relativeBase.length() == 0 ? fileName
227                             : (relativeBase + '/' + fileName);
228                         list.addAll(findFiles(fullName, pattern, fullPath,
229                             recursive, relativeName));
230                     }
231                 }
232                 else if (fullPath)
233                 {
234                     list.add(fullName);
235                 }
236                 else
237                 {
238                     String relativeName = relativeBase.length() == 0 ? fileName
239                         : (relativeBase + '/' + fileName);
240                     list.add(relativeName);
241                 }
242             }
243         }
244         return list;
245     }
246
247     public static void mkdir(String dir)
248     {
249         try
250         {
251             new File(dir).mkdirs();
252         }
253         catch (Exception ex)
254         {
255             throw new SystemException(ex);
256         }
257     }
258
259     public static void mkdirs(String file)
260     {
261         try
262         {
263             file = file.replace('/', File.separatorChar);
264             int pos = file.lastIndexOf(File.separatorChar);
265             if (pos != -1)
266             {
267                 String dir = file.substring(0, pos);
268                 mkdir(dir);
269             }
270         }
271         catch (Exception ex)
272         {
273             throw new SystemException(ex);
274         }
275     }
276
277     public static String newTempDir()
278     {
279         String tempDir = SystemProperties.getTempDir();
280         synchronized (_tempIndexLock)
281         {
282             tempDir += "/" + (++_tempIndex);
283         }
284         tempDir = pretty(tempDir);
285         deleteFilesInDir(tempDir);
286         mkdirs(tempDir + "/x.x");
287         return tempDir;
288     }
289
290     public static String pretty(String file)
291     {
292         try
293         {
294             return new File(file).getCanonicalPath();
295         }
296         catch (Exception ignore)
297         {
298             return file.replace('/', File.separatorChar);
299         }
300     }
301
302     /**
303      ** Read all bytes of a file into an array.
304      **/

305     public static byte[] readBytes(String fileName)
306     {
307         try
308         {
309             ByteArrayOutputStream bytes = new ByteArrayOutputStream();
310             InputStream input = new BufferedInputStream(new FileInputStream(fileName));
311             int c;
312             while ((c = input.read()) != -1)
313             {
314                 bytes.write((byte)c);
315             }
316             input.close();
317             return bytes.toByteArray();
318         }
319         catch (IOException ex)
320         {
321             throw new SystemException(ex);
322         }
323     }
324
325     public static String readLines(String fileName)
326     {
327         return readLines(fileName, false);
328     }
329
330     /**
331      ** Read all lines of a file into a string, optionally removing comments.
332      **/

333     public static String readLines(String fileName, boolean removeTopLevelComments)
334     {
335         try
336         {
337             StringBuffer code = new StringBuffer();
338             BufferedReader input = new BufferedReader(new FileReader(fileName));
339             String line;
340             while ((line = input.readLine()) != null)
341             {
342                 if (removeTopLevelComments && line.length() >= 3)
343                 {
344                     char c1 = line.charAt(1);
345                     char c2 = line.charAt(2);
346                     if (c1 == '*' && c2 == '*')
347                     {
348                         continue;
349                     }
350                 }
351                 code.append(line);
352                 code.append('\n');
353             }
354             input.close();
355             return code.toString();
356         }
357         catch (IOException ex)
358         {
359             throw new SystemException(ex);
360         }
361     }
362 }
363
Popular Tags