📄 fileutils.java
字号:
*/ public String toVMSPath(File f) { // format: "DEVICE:[DIR.SUBDIR]FILE" String osPath; String path = normalize(f.getAbsolutePath()).getPath(); String name = f.getName(); boolean isAbsolute = path.charAt(0) == File.separatorChar; // treat directories specified using .DIR syntax as files boolean isDirectory = f.isDirectory() && !name.regionMatches(true, name.length() - 4, ".DIR", 0, 4); String device = null; StringBuffer directory = null; String file = null; int index = 0; if (isAbsolute) { index = path.indexOf(File.separatorChar, 1); if (index == -1) { return path.substring(1) + ":[000000]"; } else { device = path.substring(1, index++); } } if (isDirectory) { directory = new StringBuffer(path.substring(index). replace(File.separatorChar, '.')); } else { int dirEnd = path.lastIndexOf(File.separatorChar, path.length()); if (dirEnd == -1 || dirEnd < index) { file = path.substring(index); } else { directory = new StringBuffer(path.substring(index, dirEnd). replace(File.separatorChar, '.')); index = dirEnd + 1; if (path.length() > index) { file = path.substring(index); } } } if (!isAbsolute && directory != null) { directory.insert(0, '.'); } osPath = ((device != null) ? device + ":" : "") + ((directory != null) ? "[" + directory + "]" : "") + ((file != null) ? file : ""); return osPath; } /** * Create a temporary file in a given directory. * * <p>The file denoted by the returned abstract pathname did not * exist before this method was invoked, any subsequent invocation * of this method will yield a different file name.</p> * <p> * The filename is prefixNNNNNsuffix where NNNN is a random number. * </p> * <p>This method is different from File.createTempFile() of JDK 1.2 * as it doesn't create the file itself. It uses the location pointed * to by java.io.tmpdir when the parentDir attribute is null.</p> * * @param prefix prefix before the random number. * @param suffix file extension; include the '.'. * @param parentDir Directory to create the temporary file in; * java.io.tmpdir used if not specified. * * @return a File reference to the new temporary file. * @since Ant 1.5 */ public File createTempFile(String prefix, String suffix, File parentDir) { return createTempFile(prefix, suffix, parentDir, false); } /** * Create a temporary file in a given directory. * * <p>The file denoted by the returned abstract pathname did not * exist before this method was invoked, any subsequent invocation * of this method will yield a different file name.</p> * <p> * The filename is prefixNNNNNsuffix where NNNN is a random number. * </p> * <p>This method is different from File.createTempFile() of JDK 1.2 * as it doesn't create the file itself. It uses the location pointed * to by java.io.tmpdir when the parentDir attribute is null.</p> * * @param prefix prefix before the random number. * @param suffix file extension; include the '.'. * @param parentDir Directory to create the temporary file in; * @param deleteOnExit whether to set the tempfile for deletion on * normal VM exit. * java.io.tmpdir used if not specified. * * @return a File reference to the new temporary file. * @since Ant 1.7 */ public File createTempFile(String prefix, String suffix, File parentDir, boolean deleteOnExit) { File result = null; String parent = (parentDir == null) ? System.getProperty("java.io.tmpdir") : parentDir.getPath(); DecimalFormat fmt = new DecimalFormat("#####"); synchronized (rand) { do { result = new File(parent, prefix + fmt.format(Math.abs(rand.nextInt())) + suffix); } while (result.exists()); } if (deleteOnExit) { result.deleteOnExit(); } return result; } /** * Compares the contents of two files. * * @param f1 the file whose content is to be compared. * @param f2 the other file whose content is to be compared. * * @return true if the content of the files is the same. * * @throws IOException if the files cannot be read. */ public boolean contentEquals(File f1, File f2) throws IOException { return contentEquals(f1, f2, false); } /** * Compares the contents of two files. * * @param f1 the file whose content is to be compared. * @param f2 the other file whose content is to be compared. * @param textfile true if the file is to be treated as a text file and * differences in kind of line break are to be ignored. * * @return true if the content of the files is the same. * * @throws IOException if the files cannot be read. * @since Ant 1.6.3 */ public boolean contentEquals(File f1, File f2, boolean textfile) throws IOException { return ResourceUtils.contentEquals( new FileResource(f1), new FileResource(f2), textfile); } /** * This was originally an emulation of {@link File#getParentFile} for JDK 1.1, * but it is now implemented using that method (Ant 1.6.3 onwards). * @param f the file whose parent is required. * @return the given file's parent, or null if the file does not have a * parent. * @since 1.10 * @deprecated since 1.7. * Just use {@link File#getParentFile} directly. */ public File getParentFile(File f) { return (f == null) ? null : f.getParentFile(); } /** * Read from reader till EOF. * @param rdr the reader from which to read. * @return the contents read out of the given reader. * * @throws IOException if the contents could not be read out from the * reader. */ public static final String readFully(Reader rdr) throws IOException { return readFully(rdr, BUF_SIZE); } /** * Read from reader till EOF. * * @param rdr the reader from which to read. * @param bufferSize the buffer size to use when reading. * * @return the contents read out of the given reader. * * @throws IOException if the contents could not be read out from the * reader. */ public static final String readFully(Reader rdr, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size must be greater " + "than 0"); } final char[] buffer = new char[bufferSize]; int bufferLength = 0; StringBuffer textBuffer = null; while (bufferLength != -1) { bufferLength = rdr.read(buffer); if (bufferLength > 0) { textBuffer = (textBuffer == null) ? new StringBuffer() : textBuffer; textBuffer.append(new String(buffer, 0, bufferLength)); } } return (textBuffer == null) ? null : textBuffer.toString(); } /** * This was originally an emulation of File.createNewFile for JDK 1.1, * but it is now implemented using that method (Ant 1.6.3 onwards). * * <p>This method has historically <strong>not</strong> guaranteed that the * operation was atomic. In its current implementation it is. * * @param f the file to be created. * @return true if the file did not exist already. * @throws IOException on error. * @since Ant 1.5 */ public boolean createNewFile(File f) throws IOException { return f.createNewFile(); } /** * Create a new file, optionally creating parent directories. * * @param f the file to be created. * @param mkdirs <code>boolean</code> whether to create parent directories. * @return true if the file did not exist already. * @throws IOException on error. * @since Ant 1.6.3 */ public boolean createNewFile(File f, boolean mkdirs) throws IOException { File parent = f.getParentFile(); if (mkdirs && !(parent.exists())) { parent.mkdirs(); } return f.createNewFile(); } /** * Checks whether a given file is a symbolic link. * * <p>It doesn't really test for symbolic links but whether the * canonical and absolute paths of the file are identical--this * may lead to false positives on some platforms.</p> * * @param parent the parent directory of the file to test * @param name the name of the file to test. * * @return true if the file is a symbolic link. * @throws IOException on error. * @since Ant 1.5 */ public boolean isSymbolicLink(File parent, String name) throws IOException { if (parent == null) { File f = new File(name); parent = f.getParentFile(); name = f.getName(); } File toTest = new File(parent.getCanonicalPath(), name); return !toTest.getAbsolutePath().equals(toTest.getCanonicalPath()); } /** * Removes a leading path from a second path. * * @param leading The leading path, must not be null, must be absolute. * @param path The path to remove from, must not be null, must be absolute. * * @return path's normalized absolute if it doesn't start with * leading; path's path with leading's path removed otherwise. * * @since Ant 1.5 */ public String removeLeadingPath(File leading, File path) { String l = normalize(leading.getAbsolutePath()).getAbsolutePath(); String p = normalize(path.getAbsolutePath()).getAbsolutePath(); if (l.equals(p)) { return ""; } // ensure that l ends with a / // so we never think /foo was a parent directory of /foobar if (!l.endsWith(File.separator)) { l += File.separator; } return (p.startsWith(l)) ? p.substring(l.length()) : p; } /** * Learn whether one path "leads" another. * @param leading The leading path, must not be null, must be absolute. * @param path The path to remove from, must not be null, must be absolute. * @return true if path starts with leading; false otherwise. * @since Ant 1.7 */ public boolean isLeadingPath(File leading, File path) { String l = normalize(leading.getAbsolutePath()).getAbsolutePath(); String p = normalize(path.getAbsolutePath()).getAbsolutePath(); if (l.equals(p)) { return true; } // ensure that l ends with a / // so we never think /foo was a parent directory of /foobar if (!l.endsWith(File.separator)) { l += File.separator; } return p.startsWith(l); } /** * Constructs a <code>file:</code> URI that represents the * external form of the given pathname. * * <p>Will be an absolute URI if the given path is absolute.</p> * * <p>This code encodes non ASCII characters too.</p> * * <p>The coding of the output is the same as what File.toURI().toASCIIString() produces</p> * * See <a href="http://www.w3.org/TR/xml11/#dt-sysid">dt-sysid</a> * which makes some mention of how * characters not supported by URI Reference syntax should be escaped. * * @param path the path in the local file system. * @return the URI version of the local path. * @since Ant 1.6 */ public String toURI(String path) { // #8031: first try Java 1.4. Class uriClazz = null; try { uriClazz = Class.forName("java.net.URI"); } catch (ClassNotFoundException e) { // OK, Java 1.3. } if (uriClazz != null) { try { File f = new File(path).getAbsoluteFile(); java.lang.reflect.Method toURIMethod = File.class.getMethod("toURI", new Class[0]); Object uriObj = toURIMethod.invoke(f, new Object[] {}); java.lang.reflect.Method toASCIIStringMethod = uriClazz.getMethod("toASCIIString", new Class[0]); return (String) toASCIIStringMethod.invoke(uriObj, new Object[] {}); } catch (Exception e) { // Reflection problems? Should not happen, debug. e.printStackTrace(); } } boolean isDir = new File(path).isDirectory(); StringBuffer sb = new StringBuffer("file:"); path = resolveFile(null, path).getPath(); sb.append("//"); // add an extra slash for filesystems with drive-specifiers if (!path.startsWith(File.separator)) { sb.append("/"); } path = path.replace('\\', '/'); try { sb.append(Locator.encodeURI(path)); } catch (UnsupportedEncodingException exc) { throw new BuildException(exc); } if (isDir && !path.endsWith("/")) { sb.append('/'); } return sb.toString(); } /** * Constructs a file path from a <code>file:</code> URI. * * <p>Will be an absolute path if the given URI is absolute.</p> * * <p>Swallows '%' that are not followed by two characters, * doesn't deal with non-ASCII characters.</p> * * @param uri the URI designating a file in the local filesystem.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -