FilePath.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // Copyright (c) 2007, 2014 Per M.A. Bothner.
  2. // This is free software; for terms and warranty disclaimer see ../../COPYING.
  3. package gnu.kawa.io;
  4. import java.io.*;
  5. import java.net.*;
  6. import gnu.mapping.*;
  7. /** A wrapper around a {@code java.io.File} that extends {@code Path}. */
  8. public class FilePath
  9. extends Path
  10. /* #ifdef JAVA5 */
  11. implements Comparable<FilePath>
  12. /* #else */
  13. // implements Comparable
  14. /* #endif */
  15. {
  16. final File file;
  17. /** Usually the same as {@code file.toString()}.
  18. * One important difference: {@code isDirectory} is true
  19. * if {@code path} ends with the {@code '/'} or the {@code separatorChar}.
  20. * The original String if constructed from a String.
  21. */
  22. final String path;
  23. private FilePath (File file)
  24. {
  25. this.file = file;
  26. this.path = file.toString();
  27. }
  28. private FilePath (File file, String path)
  29. {
  30. this.file = file;
  31. this.path = path;
  32. }
  33. public static FilePath valueOf(String str) {
  34. String orig = str;
  35. /* FIXME: Should we expand '~'?
  36. Issues: is (path "~/bar") absolute?
  37. What about: (base:resolve "~/bar") ?
  38. What if base above isn't a FilePath?
  39. int len = str.length();
  40. if (len > 0 && str.charAt(0) == '~' && File.separatorChar == '/') {
  41. if (len == 1 || str.charAt(1) == '/') {
  42. String user = System.getProperty("user.home");
  43. if (user != null)
  44. str = user + str.substring(1);
  45. } else {
  46. // We don't support '~USER/...' Do that using /bin/sh. FIXME
  47. }
  48. }
  49. */
  50. File f;
  51. if (str.startsWith("file:")) {
  52. try {
  53. f = new File(new URI(str));
  54. } catch (URISyntaxException ex) {
  55. throw new RuntimeException("bad file: URI syntax - "+str, ex);
  56. }
  57. } else
  58. f = new File(str);
  59. return new FilePath(f, orig);
  60. }
  61. public static FilePath valueOf(File file) {
  62. return new FilePath(file);
  63. }
  64. public static FilePath valueOf(URI uri) {
  65. if (uri.isAbsolute())
  66. return FilePath.valueOf(new File(uri));
  67. String ustr = uri.toString();
  68. char sep = File.separatorChar;
  69. if (sep != '/')
  70. ustr = ustr.replace('/', sep);
  71. return new FilePath(new File(ustr));
  72. }
  73. public static FilePath coerceToFilePathOrNull(Object path) {
  74. if (path instanceof FilePath)
  75. return (FilePath) path;
  76. if (path instanceof URIPath)
  77. path = ((URIPath) path).uri;
  78. if (path instanceof URI)
  79. return FilePath.valueOf((URI) path);
  80. if (path instanceof File)
  81. return FilePath.valueOf((File) path);
  82. String str;
  83. if (path instanceof CharSequence) // FIXME: || UntypedAtomic
  84. str = path.toString();
  85. else
  86. return null;
  87. return FilePath.valueOf(str);
  88. }
  89. public static FilePath makeFilePath(Object arg) {
  90. FilePath path = coerceToFilePathOrNull(arg);
  91. if (path == null)
  92. throw new WrongType((String) null, WrongType.ARG_CAST,
  93. arg, "filepath");
  94. return path;
  95. }
  96. public boolean isAbsolute() {
  97. return this == Path.userDirPath || file.isAbsolute();
  98. }
  99. /** Does this path represent a directory?
  100. * It is assumed to be a directory if the path ends with '/'
  101. * or File.separatorChar - or if the file exists and is a directory.
  102. */
  103. @Override
  104. public boolean isDirectory() {
  105. int len = path.length();
  106. if (len > 0) {
  107. char last = path.charAt(len - 1);
  108. if (last == '/' || last == File.separatorChar)
  109. return true;
  110. }
  111. return toFile().isDirectory();
  112. }
  113. @Override
  114. public void deleteFile() throws IOException {
  115. /* #ifdef JAVA7 */
  116. java.nio.file.Files.delete(toNPath());
  117. /* #else */
  118. // if (! toFile().delete())
  119. // throw new IOException("cannot delete - "+this);
  120. /* #endif */
  121. }
  122. public long getLastModified ()
  123. {
  124. return toFile().lastModified();
  125. }
  126. public boolean exists ()
  127. {
  128. return toFile().exists();
  129. }
  130. public long getContentLength ()
  131. {
  132. File f = toFile();
  133. long length = f.length();
  134. return length == 0 && ! f.exists() ? -1 : length;
  135. }
  136. public String getPath ()
  137. {
  138. return file.getPath();
  139. }
  140. public String getLast ()
  141. {
  142. return file.getName();
  143. }
  144. public
  145. /* #ifdef JAVA5 */
  146. FilePath
  147. /* #else */
  148. // Path
  149. /* #endif */
  150. getParent ()
  151. {
  152. File parent = file.getParentFile();
  153. if (parent == null)
  154. return null;
  155. else
  156. return FilePath.valueOf(parent);
  157. }
  158. public int compareTo (FilePath path)
  159. {
  160. return file.compareTo(path.file);
  161. }
  162. /* #ifndef JAVA5 */
  163. // public int compareTo (Object obj)
  164. // {
  165. // return compareTo((FilePath) obj);
  166. // }
  167. /* #endif */
  168. public boolean equals (Object obj)
  169. {
  170. return obj instanceof FilePath && file.equals(((FilePath) obj).file);
  171. }
  172. public int hashCode ()
  173. {
  174. return file.hashCode();
  175. }
  176. public String toString ()
  177. {
  178. return path;
  179. }
  180. public File toFileRaw ()
  181. {
  182. return file;
  183. }
  184. public File toFile() {
  185. if (file.isAbsolute())
  186. return file;
  187. Path cur = currentPath();
  188. if (cur == userDirPath)
  189. return file;
  190. return ((FilePath) cur.resolve(this)).toFileRaw();
  191. }
  192. public URL toURL ()
  193. {
  194. if (! isAbsolute())
  195. return getAbsolute().toURL();
  196. try
  197. {
  198. return file.toURI().toURL();
  199. }
  200. catch (Exception ex)
  201. {
  202. throw WrappedException.wrapIfNeeded(ex);
  203. }
  204. }
  205. public URI toUri() {
  206. try {
  207. if (file.isAbsolute())
  208. return file.toURI();
  209. /* We don't want to just use File.toURI(),
  210. because that turns a relative File into an absolute URI. */
  211. String fname = path;
  212. char fileSep = File.separatorChar;
  213. if (fileSep != '/')
  214. fname = fname.replace(fileSep, '/');
  215. int len = fname.length();
  216. if (len > 0 && fname.charAt(len-1) != '/'
  217. && isDirectory())
  218. fname = fname + '/';
  219. return new URI(null, null, fname, null);
  220. } catch (Exception ex) {
  221. throw WrappedException.wrapIfNeeded(ex);
  222. }
  223. }
  224. public InputStream openInputStream() throws IOException {
  225. return new FileInputStream(toFile());
  226. }
  227. public OutputStream openOutputStream() throws IOException {
  228. return new FileOutputStream(toFile());
  229. }
  230. public OutputStream openAppendStream() throws IOException {
  231. return new FileOutputStream(toFile(), true);
  232. }
  233. public String getScheme() {
  234. return isAbsolute() ? "file" : null;
  235. }
  236. public Path resolve(String relative) {
  237. if (Path.uriSchemeSpecified(relative)) {
  238. if (relative.startsWith("file:"))
  239. return FilePath.valueOf(relative);
  240. else
  241. return URLPath.valueOf(relative);
  242. }
  243. if (relative.length() == 0)
  244. return this;
  245. File rfile = new File(relative);
  246. if (! rfile.isAbsolute())
  247. rfile = new File(isDirectory() ? file : file.getParentFile(),
  248. rfile.toString());
  249. return new FilePath(rfile);
  250. }
  251. public Path getCanonical ()
  252. {
  253. try
  254. {
  255. File canon = file.getCanonicalFile();
  256. if (! canon.equals(file))
  257. return valueOf(canon);
  258. }
  259. catch (Exception ex)
  260. {
  261. }
  262. return this;
  263. }
  264. /* #ifdef JAVA7 */
  265. /** Convert to a {@code java.nio.file.Path} instance.
  266. * Unlike the overriden base method, this cannot
  267. * throw {@code FileSystemNotFoundException}.
  268. * Use caution if this is a relative path and the {@code currentPath()}
  269. * is not the default path, since {@code java.nio} assumes a relative path
  270. * is relative to the default directory.
  271. */
  272. @Override
  273. public java.nio.file.Path toNPath() {
  274. return file.toPath();
  275. }
  276. @Override
  277. public byte[] readAllBytes() throws IOException {
  278. Path rpath = this;
  279. if (! isAbsolute()) {
  280. Path cur = currentPath();
  281. if (cur != Path.userDirPath)
  282. rpath = cur.resolve(this);
  283. }
  284. return java.nio.file.Files.readAllBytes(rpath.toNPath());
  285. }
  286. /* #endif */
  287. }