KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > File


1 /*
2  * File.java
3  *
4  * Copyright (C) 1998-2002 Peter Graves
5  * $Id: File.java,v 1.13 2002/12/09 15:00:11 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j;
23
24 import java.io.BufferedReader JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileNotFoundException JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.FilenameFilter JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import java.io.RandomAccessFile JavaDoc;
32 import java.lang.reflect.Method JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35
36 public class File implements Comparable JavaDoc
37 {
38     public static final int PROTOCOL_FILE = 0;
39     public static final int PROTOCOL_HTTP = 1;
40     public static final int PROTOCOL_HTTPS = 2;
41     public static final int PROTOCOL_FTP = 3;
42     public static final int PROTOCOL_SSH = 4;
43
44     public static final String JavaDoc PREFIX_HTTP = "http://";
45     public static final String JavaDoc PREFIX_HTTPS = "https://";
46     public static final String JavaDoc PREFIX_FTP = "ftp://";
47     public static final String JavaDoc PREFIX_SSH = "ssh://";
48     public static final String JavaDoc PREFIX_FILE = "file://";
49
50     public static final String JavaDoc PREFIX_LOCAL_HOST =
51         LocalFile.getLocalHostName().concat(":");
52
53     public static final int TYPE_UNKNOWN = 0;
54     public static final int TYPE_FILE = 1;
55     public static final int TYPE_DIRECTORY = 2;
56     public static final int TYPE_LINK = 3;
57
58     private static final boolean ignoreCase = Platform.isPlatformWindows();
59
60     private java.io.File JavaDoc file;
61
62     protected boolean isRemote;
63     protected String JavaDoc hostName;
64     protected String JavaDoc userName;
65     protected String JavaDoc password;
66     protected int port;
67     protected int type; // unknown, file, directory, link
68
protected String JavaDoc canonicalPath;
69     protected int protocol = PROTOCOL_FILE;
70
71     private String JavaDoc encoding;
72
73     protected File()
74     {
75     }
76
77     private File(String JavaDoc path)
78     {
79         file = new java.io.File JavaDoc(path);
80         if (Platform.isPlatformWindows() && path.indexOf('*') >= 0) {
81             // Workaround for Windows 2000, Java 1.1.8.
82
canonicalPath = path;
83         } else {
84             try {
85                 canonicalPath = file.getCanonicalPath();
86             }
87             catch (IOException JavaDoc e) {
88                 canonicalPath = path;
89             }
90         }
91     }
92
93     private File(String JavaDoc host, String JavaDoc path, int protocol)
94     {
95         Debug.assertTrue(protocol != PROTOCOL_FTP);
96         isRemote = host != null;
97         hostName = host;
98         canonicalPath = path;
99         this.protocol = protocol;
100     }
101
102     public static File getInstance(String JavaDoc name)
103     {
104         if (name == null)
105             return null;
106         int length = name.length();
107         if (length >= 2) {
108             // Name may be enclosed in quotes.
109
if (name.charAt(0) == '"' && name.charAt(length-1) == '"') {
110                 name = name.substring(1, length-1);
111                 length -= 2;
112             }
113         }
114         if (length == 0)
115             return null;
116
117         if (name.startsWith(PREFIX_FTP))
118             return FtpFile.getFtpFile(name);
119         if (name.startsWith(PREFIX_HTTP) || name.startsWith(PREFIX_HTTPS))
120             return HttpFile.getHttpFile(name);
121         if (name.startsWith(PREFIX_SSH))
122             return SshFile.getSshFile(name);
123
124         // Local file.
125
if (name.startsWith(PREFIX_FILE)) {
126             name = name.substring(PREFIX_FILE.length());
127             if (name.length() == 0)
128                 return null;
129         } else if (name.startsWith(PREFIX_LOCAL_HOST)) {
130             name = name.substring(PREFIX_LOCAL_HOST.length());
131             if (name.length() == 0)
132                 return null;
133         } else if (name.charAt(0) == ':') {
134             name = name.substring(1);
135             if (--length == 0)
136                 return null;
137         }
138         name = normalize(name);
139
140         if (Platform.isPlatformWindows() && name.startsWith("\\")) {
141             // Check for UNC path.
142
String JavaDoc drive = getDrive(name);
143             if (drive == null) {
144                 drive = getDrive(System.getProperty("user.dir"));
145                 if (drive != null)
146                     name = drive.concat(name);
147             }
148         }
149
150         // This might return null.
151
name = canonicalize(name, LocalFile.getSeparator());
152
153         return name != null ? new File(name) : null;
154     }
155
156     protected boolean initRemote(String JavaDoc name, String JavaDoc prefix)
157     {
158         if (!name.startsWith(prefix))
159             return false;
160         name = name.substring(prefix.length());
161         int index = name.indexOf('/');
162
163         // "ftp:///", "ssh:///" are invalid.
164
if (index == 0)
165             return false;
166
167         String JavaDoc s;
168         if (index > 0) {
169             s = name.substring(0, index);
170             canonicalPath = canonicalize(name.substring(index), "/");
171         } else {
172             s = name;
173             canonicalPath = "";
174         }
175
176         // Host name may be preceded by username and password ("user:password@host") and/or
177
// followed by port number ("user:password@host:port").
178
index = s.indexOf('@');
179         if (index >= 0) {
180             // String contains '@'.
181
String JavaDoc before = s.substring(0, index);
182
183             // Shorten s to what's left (host and port).
184
s = s.substring(index+1);
185
186             index = before.indexOf(':');
187             if (index >= 0) {
188                 userName = before.substring(0, index);
189                 password = before.substring(index+1);
190             } else {
191                 // No ':', no password.
192
userName = before;
193             }
194         } else if (protocol != PROTOCOL_FTP) // Don't break anonymous FTP!
195
userName = System.getProperty("user.name");
196         index = s.indexOf(':');
197         if (index >= 0) {
198             // String contains ':', port specified.
199
hostName = s.substring(0, index);
200             try {
201                 port = Integer.parseInt(s.substring(index+1));
202             }
203             catch (NumberFormatException JavaDoc e) {
204                 Log.error(e);
205             }
206         } else {
207             // No ':', port not specified.
208
hostName = s;
209         }
210         return true;
211     }
212
213     public static File getInstance(File directory, String JavaDoc name)
214     {
215         if (name == null)
216             return null;
217         int length = name.length();
218         if (length >= 2) {
219             // Name may be enclosed in quotes.
220
if (name.charAt(0) == '"' && name.charAt(length-1) == '"') {
221                 name = name.substring(1, length-1);
222                 length -= 2;
223             }
224         }
225         if (length == 0)
226             return null;
227
228         if (hasRemotePrefix(name)) {
229             // Ignore directory.
230
return getInstance(canonicalize(name, "/"));
231         }
232         if (hasLocalPrefix(name)) {
233             // Fully qualified name.
234
return getInstance(name);
235         }
236
237         if (directory == null)
238             return null;
239
240         if (directory instanceof HttpFile)
241             return HttpFile.getHttpFile((HttpFile) directory, name);
242         if (directory instanceof FtpFile)
243             return FtpFile.getFtpFile((FtpFile) directory, name);
244         if (directory instanceof SshFile)
245             return SshFile.getSshFile((SshFile) directory, name);
246         if (directory.isRemote) {
247             Debug.assertTrue(false);
248             File file = new File();
249             file.isRemote = true;
250             file.protocol = directory.protocol;
251             file.hostName = directory.hostName;
252             if (Utilities.isFilenameAbsolute(name))
253                 file.canonicalPath = canonicalize(name, "/");
254             else
255                 file.canonicalPath = canonicalize(appendNameToPath(directory.canonicalPath(), name, '/'), "/");
256             return file;
257         }
258
259         // Local file.
260
name = normalize(name);
261         if (Utilities.isFilenameAbsolute(name)) {
262             // Name is absolute.
263
if (Platform.isPlatformWindows() && name.startsWith("\\")) {
264                 String JavaDoc drive = getDrive(name);
265                 if (drive == null) {
266                     drive = directory.getDrive();
267                     if (drive != null)
268                         name = drive.concat(name);
269                 }
270             }
271         } else
272             name = appendNameToPath(directory.canonicalPath(), name);
273         name = canonicalize(name, LocalFile.getSeparator());
274         if (name == null)
275             return null;
276         return new File(name);
277     }
278
279     public static File getInstance(String JavaDoc host, String JavaDoc path, int protocol)
280     {
281         if (host == null)
282             return null;
283         if (path == null)
284             return null;
285
286         if (protocol != PROTOCOL_HTTP && protocol != PROTOCOL_HTTPS && protocol != PROTOCOL_FTP)
287             throw new NotSupportedException();
288
289         if (protocol == PROTOCOL_FTP)
290             return FtpFile.getFtpFile(host, path);
291
292         return new File(host, path, protocol);
293     }
294
295     public File getRoot()
296     {
297         if (Platform.isPlatformWindows())
298             return new File(getDrive() + "\\");
299
300         // Unix.
301
return new File("/");
302     }
303
304     public static File[] listRoots()
305     {
306         java.io.File JavaDoc[] files = (java.io.File JavaDoc[]) java.io.File.listRoots();
307         File[] list = new File[files.length];
308         for (int i = 0; i < files.length; i++) {
309             list[i] = new File();
310             list[i].canonicalPath = files[i].getPath();
311             list[i].file = new java.io.File JavaDoc(list[i].canonicalPath);
312         }
313         return list;
314     }
315
316     public String JavaDoc getSeparator()
317     {
318         return java.io.File.separator;
319     }
320
321     public char getSeparatorChar()
322     {
323         return java.io.File.separatorChar;
324     }
325
326     public String JavaDoc getDrive()
327     {
328         if (Platform.isPlatformWindows())
329             return getDrive(canonicalPath);
330
331         return null;
332     }
333
334     private static String JavaDoc getDrive(String JavaDoc s)
335     {
336         if (s != null && s.length() >= 2) {
337             if (s.charAt(0) == '\\' && s.charAt(1) == '\\') {
338                 // UNC path.
339
int index = s.indexOf('\\', 2);
340                 if (index >= 0) {
341                     index = s.indexOf('\\', index + 1);
342                     if (index >= 0)
343                         return s.substring(0, index);
344                 }
345             } else if (s.charAt(1) == ':') {
346                 String JavaDoc prefix = s.substring(0, 2).toUpperCase();
347                 char c = prefix.charAt(0);
348                 if (c >= 'A' && c <= 'Z')
349                     return prefix;
350             }
351         }
352         return null;
353     }
354
355     protected static String JavaDoc canonicalize(String JavaDoc name, String JavaDoc sep)
356     {
357         String JavaDoc prefix = null;
358         if (name.startsWith(PREFIX_HTTP)) {
359             prefix = PREFIX_HTTP;
360             sep = "/";
361         } else if (name.startsWith(PREFIX_HTTPS)){
362             prefix = PREFIX_HTTPS;
363             sep = "/";
364         } else if (name.startsWith(PREFIX_FTP)) {
365             prefix = PREFIX_FTP;
366             sep = "/";
367         } else if (name.startsWith(PREFIX_SSH)) {
368             prefix = PREFIX_SSH;
369             sep = "/";
370         } else if (Platform.isPlatformWindows())
371             prefix = getDrive(name);
372
373         if (prefix != null)
374             name = name.substring(prefix.length());
375
376         if (sep == null)
377             sep = LocalFile.getSeparator();
378
379         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(name, sep);
380         final int numTokens = st.countTokens();
381         String JavaDoc[] array = new String JavaDoc[numTokens];
382         int count = 0;
383         for (int i = 0; i < numTokens; i++) {
384             String JavaDoc token = st.nextToken();
385             if (token.equals("..")) {
386                 if (count > 0)
387                     --count;
388                 else
389                     return null;
390             } else if (!token.equals("."))
391                 array[count++] = token;
392         }
393
394         FastStringBuffer sb = new FastStringBuffer(256);
395         if (prefix != null)
396             sb.append(prefix);
397         if (count == 0)
398             sb.append(sep);
399         else {
400             for (int i = 0; i < count; i++) {
401                 if (!sb.toString().endsWith(sep))
402                     sb.append(sep);
403                 sb.append(array[i]);
404             }
405         }
406         return sb.toString();
407     }
408
409     public static String JavaDoc normalize(String JavaDoc name)
410     {
411         if (hasRemotePrefix(name))
412             return name;
413
414         if (name.equals("~") || name.equals("~/"))
415             name = Utilities.getUserHome();
416         else if (name.startsWith("~/"))
417             name = appendNameToPath(Utilities.getUserHome(), name.substring(2));
418
419         if (Platform.isPlatformWindows()) {
420             if (name.length() >= 4) {
421                 if (name.charAt(0) == '/' && name.charAt(1) == '/' && name.charAt(3) == '/') {
422                     // Convert Cygwin format to drive letter plus colon.
423
char c = name.charAt(2);
424                     if (c >= 'a' && c <= 'z') {
425                         // e.g. "//d/"
426
name = c + ":\\" + name.substring(4);
427                     }
428                 }
429             }
430         }
431
432         char toBeReplaced = LocalFile.getSeparatorChar() == '/' ? '\\' : '/';
433         return name.replace(toBeReplaced, LocalFile.getSeparatorChar());
434     }
435
436     public static boolean hasRemotePrefix(String JavaDoc name)
437     {
438         if (name.startsWith(PREFIX_HTTP))
439             return true;
440         if (name.startsWith(PREFIX_HTTPS))
441             return true;
442         if (name.startsWith(PREFIX_FTP))
443             return true;
444         if (name.startsWith(PREFIX_SSH))
445             return true;
446         return false;
447     }
448
449     public static boolean hasLocalPrefix(String JavaDoc name)
450     {
451         if (name.startsWith(PREFIX_FILE))
452             return true;
453         if (name.startsWith(PREFIX_LOCAL_HOST))
454             return true;
455         if (name.length() > 0 && name.charAt(0) == ':')
456             return true;
457         return false;
458     }
459
460     // Uses platform-specific separator char.
461
public final static String JavaDoc appendNameToPath(String JavaDoc path, String JavaDoc name)
462     {
463         return appendNameToPath(path, name, LocalFile.getSeparatorChar());
464     }
465
466     public static String JavaDoc appendNameToPath(String JavaDoc path, String JavaDoc name, char separator)
467     {
468         int pathLength = path.length();
469
470         if (pathLength > 0 && name.length() > 0) {
471             // If path does not end with a separator and name does not begin
472
// with a separator, add a separator when concatenating the strings.
473
if (path.charAt(pathLength - 1) != separator)
474                 if (name.charAt(0) != separator)
475                     return path + separator + name;
476
477             // If path ends with a separator (e.g. "/") and name begins with a
478
// separator, remove one of the separators before concatenating the
479
// strings.
480
if (path.charAt(pathLength - 1) == separator)
481                 if (name.charAt(0) == separator)
482                     return path + name.substring(1);
483         }
484
485         return path + name;
486     }
487
488     public String JavaDoc getCanonicalPath() throws IOException JavaDoc
489     {
490         if (canonicalPath == null) {
491             if (!isRemote) {
492                 if (file != null)
493                     canonicalPath = file.getCanonicalPath();
494             }
495         }
496         return canonicalPath;
497     }
498
499     // Like getCanonicalPath(), but doesn't throw an exception.
500
public final synchronized String JavaDoc canonicalPath()
501     {
502         if (canonicalPath == null) {
503             if (file != null) {
504                 try {
505                     canonicalPath = file.getCanonicalPath();
506                 }
507                 catch (IOException JavaDoc e) {
508                     Log.error(e);
509                 }
510             }
511         }
512         return canonicalPath;
513     }
514
515     public synchronized void setCanonicalPath(String JavaDoc s)
516     {
517         if (canonicalPath == null || canonicalPath.equals(""))
518             canonicalPath = s;
519     }
520
521     public String JavaDoc netPath()
522     {
523         switch (protocol) {
524             case PROTOCOL_FILE:
525                 return LocalFile.getLocalHostName() + ':' + canonicalPath();
526             case PROTOCOL_HTTP:
527                 return PREFIX_HTTP + hostName + canonicalPath;
528             case PROTOCOL_HTTPS:
529                 return PREFIX_HTTPS + hostName + canonicalPath;
530             case PROTOCOL_FTP: {
531                 String JavaDoc s = PREFIX_FTP + hostName;
532                 if (canonicalPath != null)
533                     s += canonicalPath;
534                 return s;
535             }
536             case PROTOCOL_SSH: {
537                 String JavaDoc s = PREFIX_SSH + hostName;
538                 if (canonicalPath != null)
539                     s += canonicalPath;
540                 return s;
541             }
542         }
543         Debug.assertTrue(false);
544         return null;
545     }
546
547     public final String JavaDoc getHostName()
548     {
549         return hostName;
550     }
551
552     public final String JavaDoc getUserName()
553     {
554         return userName;
555     }
556
557     public final void setUserName(String JavaDoc userName)
558     {
559         this.userName = userName;
560     }
561
562     public final String JavaDoc getPassword()
563     {
564         return password;
565     }
566
567     public final void setPassword(String JavaDoc password)
568     {
569         this.password = password;
570     }
571
572     public final int getPort()
573     {
574         return port;
575     }
576
577     public int getProtocol()
578     {
579         return protocol;
580     }
581
582     public final boolean isLocal()
583     {
584         return !isRemote;
585     }
586
587     public final boolean isRemote()
588     {
589         return isRemote;
590     }
591
592     public String JavaDoc getName()
593     {
594         if (isRemote) {
595             int index = canonicalPath.lastIndexOf('/');
596             if (index >= 0)
597                 return canonicalPath.substring(index+1);
598             return canonicalPath;
599         }
600         if (file != null)
601             return file.getName();
602         return null;
603     }
604
605     public String JavaDoc getAbsolutePath()
606     {
607         if (isRemote)
608             return canonicalPath();
609         if (file != null) {
610             String JavaDoc absPath = file.getAbsolutePath();
611             if (Platform.isPlatformUnix() && absPath.startsWith("//")) {
612                 absPath = absPath.substring(1); // Workaround for Java 1.1.8.
613
}
614             return absPath;
615         }
616         return null;
617     }
618
619     public String JavaDoc getParent()
620     {
621         if (isRemote) {
622             if (canonicalPath.equals("/"))
623                 return null;
624             int index = canonicalPath.lastIndexOf('/');
625             if (index < 0)
626                 return null;
627             if (index == 0) // "/usr"
628
return "/";
629             return canonicalPath.substring(0, index);
630         }
631         if (file != null)
632             return file.getParent();
633         return null;
634     }
635
636     public File getParentFile()
637     {
638         if (canonicalPath() == null || canonicalPath.equals("/")) {
639             // HTTP is a special case. We might really be looking at
640
// "http://www.cnn.com/index.html", but it might appear to
641
// be "http://www.cnn.com/".
642
if (protocol == PROTOCOL_HTTP || protocol == PROTOCOL_HTTPS)
643                 return new File(hostName, "/", protocol);
644
645             return null;
646         }
647         if (isRemote){
648             int index = canonicalPath.lastIndexOf('/');
649             if (index < 0)
650                 return null;
651             if (index == 0) // "/usr"
652
return new File(hostName, "/", protocol);
653             return new File(hostName, canonicalPath.substring(0, index), protocol);
654         }
655         if (file != null && file.getParent() != null)
656             return new File(file.getParent());
657         return null;
658     }
659
660     public boolean exists()
661     {
662         if (file == null)
663             throw new NotSupportedException();
664         return file.exists();
665     }
666
667     public boolean canWrite()
668     {
669         if (file == null)
670             throw new NotSupportedException();
671         return file.canWrite();
672     }
673
674     public boolean canRead()
675     {
676         if (file == null)
677             throw new NotSupportedException();
678         return file.canRead();
679     }
680
681     public boolean isFile()
682     {
683         if (file == null)
684             throw new NotSupportedException();
685         return file.isFile();
686     }
687
688     public boolean isDirectory()
689     {
690         if (file == null)
691             throw new NotSupportedException();
692         return file.isDirectory();
693     }
694
695     public boolean isLink()
696     {
697         if (file == null)
698             throw new NotSupportedException();
699         return !canonicalPath().equals(getAbsolutePath());
700     }
701
702     public boolean isAbsolute()
703     {
704         if (file == null)
705             throw new NotSupportedException();
706         return file.isAbsolute();
707     }
708
709     public long lastModified()
710     {
711         if (file == null)
712             throw new NotSupportedException();
713         return file.lastModified();
714     }
715
716     public boolean setLastModified(long time)
717     {
718         if (file == null)
719             throw new NotSupportedException();
720         return file.setLastModified(time);
721     }
722
723     public long length()
724     {
725         if (file == null)
726             throw new NotSupportedException();
727         return file.length();
728     }
729
730     public boolean mkdir()
731     {
732         if (file == null)
733             throw new NotSupportedException();
734         return file.mkdir();
735     }
736
737     public boolean mkdirs()
738     {
739         if (file == null)
740             throw new NotSupportedException();
741         return file.mkdirs();
742     }
743
744     public boolean renameTo(File f)
745     {
746         if (file == null || f.file == null)
747             throw new NotSupportedException();
748         return file.renameTo(f.file);
749     }
750
751     public String JavaDoc[] list()
752     {
753         if (this instanceof FtpFile || this instanceof SshFile) {
754             String JavaDoc listing = getDirectoryListing();
755             if (listing == null)
756                 return null;
757             FastStringReader reader = new FastStringReader(listing);
758             ArrayList JavaDoc list = new ArrayList JavaDoc();
759             String JavaDoc s;
760             while ((s = reader.readLine()) != null) {
761                 String JavaDoc name = DirectoryEntry.getName(s);
762                 if (name == null || name.equals(".") || name.equals(".."))
763                     continue;
764                 list.add(name);
765             }
766             if (list.size() == 0)
767                 return null;
768             String JavaDoc[] names = new String JavaDoc[list.size()];
769             list.toArray(names);
770             return names;
771         }
772         if (isRemote)
773             return null;
774         if (file == null)
775             throw new NotSupportedException();
776         return file.list();
777     }
778
779     public File[] listFiles()
780     {
781         if (!isDirectory())
782             return null;
783         if (this instanceof FtpFile || this instanceof SshFile) {
784             String JavaDoc listing = getDirectoryListing();
785             if (listing == null)
786                 return null;
787             long start = System.currentTimeMillis();
788             FastStringReader reader = new FastStringReader(listing);
789             ArrayList JavaDoc list = new ArrayList JavaDoc();
790             int nameColumn = -1;
791             String JavaDoc s;
792             while ((s = reader.readLine()) != null) {
793                 if (nameColumn < 0)
794                     nameColumn = DirectoryEntry.getNameColumn(s);
795                 DirectoryEntry entry = DirectoryEntry.getDirectoryEntry(s, null);
796                 if (entry != null) {
797                     final String JavaDoc name = entry.extractName(nameColumn);
798                     if (name == null || name.equals(".") || name.equals(".."))
799                         continue;
800                     String JavaDoc path = appendNameToPath(canonicalPath(), name, '/');
801                     File file = null;
802                     if (protocol == PROTOCOL_FTP)
803                         file = new FtpFile(hostName, path, userName, password, port);
804                     else if (protocol == PROTOCOL_SSH)
805                         file = new SshFile(hostName, path, userName, password, port);
806                     else
807                         Debug.bug();
808                     if (file != null) {
809                         if (entry.isDirectory())
810                             file.type = TYPE_DIRECTORY;
811                         else if (entry.isLink())
812                             file.type = TYPE_LINK;
813                         else
814                             file.type = TYPE_FILE;
815                         list.add(file);
816                     }
817                 }
818             }
819             if (list.size() == 0)
820                 return null;
821             File[] files = new File[list.size()];
822             list.toArray(files);
823             long elapsed = System.currentTimeMillis() - start;
824             Log.debug("listFiles " + elapsed + " ms " + this);
825             return files;
826         }
827         if (isRemote)
828             return null;
829         if (file == null)
830             throw new NotSupportedException();
831         String JavaDoc[] names = file.list();
832         if (names == null)
833             return null;
834         final FastStringBuffer sb = new FastStringBuffer();
835         final String JavaDoc cp = canonicalPath();
836         File[] files = new File[names.length];
837         for (int i = 0; i < names.length; i++) {
838             sb.setText(cp);
839             sb.append(LocalFile.getSeparator());
840             sb.append(names[i]);
841             files[i] = new File(sb.toString());
842         }
843         return files;
844     }
845
846     public String JavaDoc[] list(FilenameFilter JavaDoc filter)
847     {
848         if (isRemote)
849             return null;
850         if (file == null)
851             throw new NotSupportedException();
852         return file.list(filter);
853     }
854
855     public String JavaDoc getDirectoryListing()
856     {
857         return null;
858     }
859
860     public String JavaDoc getDirectoryListing(boolean forceRefresh)
861     {
862         return null;
863     }
864
865     public boolean delete()
866     {
867         if (file == null)
868             throw new NotSupportedException();
869         return file.delete();
870     }
871
872     public int hashCode()
873     {
874         if (file == null)
875             throw new NotSupportedException();
876         return file.hashCode();
877     }
878
879     public boolean equals(Object JavaDoc obj)
880     {
881         if (this == obj)
882             return true;
883         if (!(obj instanceof File))
884             return false;
885         File f = (File) obj;
886         // Protocol.
887
if (f.protocol != protocol)
888             return false;
889         // Host name.
890
if (f.hostName == null) {
891             if (hostName != null)
892                 return false;
893         } else if (!f.hostName.equals(hostName))
894             return false;
895         // Handle pathological corner case where both canonical paths are null.
896
if (f.canonicalPath() == canonicalPath())
897             return true;
898         // At this point the canonical paths are cached for both files. If
899
// either one is null, they can't be equal.
900
if (f.canonicalPath == null || canonicalPath == null)
901             return false;
902         // Never ignore case for remote files.
903
if (ignoreCase && !isRemote)
904             return f.canonicalPath.equalsIgnoreCase(canonicalPath);
905         return f.canonicalPath.equals(canonicalPath);
906     }
907
908     public String JavaDoc toString()
909     {
910         return netPath();
911     }
912
913     public FileInputStream JavaDoc getInputStream() throws FileNotFoundException JavaDoc
914     {
915         if (isRemote)
916             throw new NotSupportedException();
917         if (file == null)
918             throw new NotSupportedException();
919         return new FileInputStream JavaDoc(file);
920     }
921
922     public FileOutputStream JavaDoc getOutputStream() throws FileNotFoundException JavaDoc
923     {
924         if (isRemote)
925             throw new NotSupportedException();
926         if (file == null)
927             throw new NotSupportedException();
928         return new FileOutputStream JavaDoc(file);
929     }
930
931     public FileOutputStream JavaDoc getOutputStream(boolean append) throws FileNotFoundException JavaDoc
932     {
933         if (isRemote)
934             throw new NotSupportedException();
935         if (file == null)
936             throw new NotSupportedException();
937         return new FileOutputStream JavaDoc(canonicalPath, append);
938     }
939
940     public RandomAccessFile JavaDoc getRandomAccessFile(String JavaDoc mode) throws FileNotFoundException JavaDoc
941     {
942         if (isRemote)
943             throw new NotSupportedException();
944         if (file == null)
945             throw new NotSupportedException();
946         return new RandomAccessFile JavaDoc(file, mode);
947     }
948
949     public final String JavaDoc getEncoding()
950     {
951         return encoding;
952     }
953
954     public final void setEncoding(String JavaDoc encoding)
955     {
956         this.encoding = encoding;
957     }
958
959     public int getPermissions()
960     {
961         int permissions = 0;
962         if (isLocal() && Platform.isPlatformUnix()) {
963             String JavaDoc[] cmdarray = {"ls", "-ld", canonicalPath()};
964             try {
965                 Process JavaDoc process = Runtime.getRuntime().exec(cmdarray);
966                 BufferedReader JavaDoc reader =
967                     new BufferedReader JavaDoc(new InputStreamReader JavaDoc(process.getInputStream()));
968                 String JavaDoc output = reader.readLine();
969                 if (output != null) {
970                     String JavaDoc s = output.substring(1, 10);
971                     if (s.length() == 9) {
972                         if (s.charAt(0) == 'r')
973                             permissions += 0400;
974                         if (s.charAt(1) == 'w')
975                             permissions += 0200;
976                         if (s.charAt(2) == 'x')
977                             permissions += 0100;
978                         if (s.charAt(3) == 'r')
979                             permissions += 040;
980                         if (s.charAt(4) == 'w')
981                             permissions += 020;
982                         if (s.charAt(5) == 'x')
983                             permissions += 010;
984                         if (s.charAt(6) == 'r')
985                             permissions += 4;
986                         if (s.charAt(7) == 'w')
987                             permissions += 2;
988                         if (s.charAt(8) == 'x')
989                             permissions += 1;
990                     }
991                     reader.close();
992                     process.getInputStream().close();
993                     process.getOutputStream().close();
994                     process.getErrorStream().close();
995                 }
996             }
997             // Feb 4 2000 5:30 PM
998
// Catch Throwable here rather than Exception.
999
// Kaffe's implementation of Runtime.exec() throws
1000
// java.lang.InternalError.
1001
catch (Throwable JavaDoc t) {
1002                Log.error(t);
1003            }
1004        }
1005        return permissions;
1006    }
1007
1008    public void setPermissions(int permissions)
1009    {
1010        if (permissions != 0 && isLocal() && Platform.isPlatformUnix()) {
1011            String JavaDoc[] cmdarray = {"chmod", Integer.toString(permissions, 8), canonicalPath()};
1012            try {
1013                Process JavaDoc process = Runtime.getRuntime().exec(cmdarray);
1014                process.getInputStream().close();
1015                process.getOutputStream().close();
1016                process.getErrorStream().close();
1017                int exitCode = process.waitFor();
1018                if (exitCode != 0)
1019                    Log.error("setPermissions exitCode = " + exitCode);
1020            }
1021            // Feb 4 2000 5:30 PM
1022
// Catch Throwable here rather than Exception.
1023
// Kaffe's implementation of Runtime.exec() throws
1024
// java.lang.InternalError.
1025
catch (Throwable JavaDoc t) {
1026                Log.error(t);
1027            }
1028        }
1029    }
1030
1031    public final int compareTo(Object JavaDoc o)
1032    {
1033        return getName().compareTo(((File)o).getName());
1034    }
1035
1036// private static void test(String dirname, String filename, String expected)
1037
// {
1038
// File dir = getInstance(dirname);
1039
// File file = getInstance(dir, filename);
1040

1041// String result;
1042

1043// if (file == null)
1044
// result = "null";
1045
// else
1046
// result = file.netPath();
1047

1048// if (Platform.isPlatformUnix() && result.equals(expected))
1049
// System.out.println(" " + dirname + " + " + filename + " => " + result);
1050
// else if (Platform.isPlatformWindows() && result.equalsIgnoreCase(expected))
1051
// System.out.println(" " + dirname + " + " + filename + " => " + result);
1052
// else
1053
// {
1054
// System.out.println("* " + dirname + " + " + filename + " => " + result);
1055
// System.out.println("*** expected " + expected + " ***");
1056
// }
1057
// }
1058

1059// public static void main(String args[])
1060
// {
1061
// if (Platform.isPlatformUnix())
1062
// {
1063
// test("/home/peter", ".", "/home/peter");
1064
// test("/home/peter", "./", "/home/peter");
1065
// test("/home/peter", "..", "/home");
1066
// test("/home/peter", "../", "/home");
1067
// test("/", "~/foo", "/home/peter/foo");
1068
// test("/", "~/../foo", "/home/foo");
1069
// test("/", "~/../../foo", "/foo");
1070
// test("/", "~/../../../foo", "null");
1071
// test("/", "~peter/foo", "/~peter/foo");
1072
// test("/home/peter", "./foo", "/home/peter/foo");
1073
// test("/home/peter", "../foo", "/home/foo");
1074
// test("/home/peter", "../../foo", "/foo");
1075
// test("/home/peter", "../../../foo", "null");
1076
// test("/home/peter", "..foo", "/home/peter/..foo");
1077
// test("/home/peter", "foo", "/home/peter/foo");
1078
// test("/home/peter", "/foo", "/foo");
1079
// }
1080
// else
1081
// {
1082
// test("\\", ".", "C:\\");
1083
// test("\\home", "\\home\\peter\\j", "C:\\home\\peter\\j");
1084
// test("d:\\home", "\\home\\peter\\j", "D:\\home\\peter\\j");
1085
// test("\\home", "d:\\home\\peter\\j", "d:\\home\\peter\\j");
1086
// test("c:\\home\\peter", ".", "C:\\home\\peter");
1087
// test("c:\\home\\peter", "..", "C:\\home");
1088
// test("c:\\home\\peter", "..\\..", "C:\\");
1089
// test("c:\\home\\peter", "..\\..\\..", "null");
1090
// test("c:\\home\\peter", "c:\\", "C:\\");
1091
// test("c:\\home\\peter", "c:\\windows", "C:\\windows");
1092
// test("c:\\home\\peter", "c:\\windows\\", "C:\\windows");
1093
// test("c:\\", ".", "C:\\");
1094
// test("c:\\", ".\\", "C:\\");
1095
// test("c:\\", "..", "null");
1096
// test("//c/", "foo", "C:\\foo");
1097
// }
1098

1099// test("http://www.cnn.com", "/virtual/1998/code/cnn.css", "http://www.cnn.com/virtual/1998/code/cnn.css");
1100
// test("http://www.cnn.com/", "/virtual/1998/code/cnn.css", "http://www.cnn.com/virtual/1998/code/cnn.css");
1101
// test("http://www.cnn.com", "http://www.swatch.com", "http://www.swatch.com/");
1102
// test("http://www.cnn.com/", "http://www.swatch.com", "http://www.swatch.com/");
1103
// test("http://www.swatch.com", "specials/live_timing/index.html", "http://www.swatch.com/specials/live_timing/index.html");
1104
// test("http://www.swatch.com/", "specials/live_timing/index.html", "http://www.swatch.com/specials/live_timing/index.html");
1105
// }
1106
}
1107
Popular Tags