📄 fileutils.java
字号:
* 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 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(); } /** * Safe read fully - do not return a null for an empty reader. * @param reader the input to read from. * @return the string. * @throws IOException if unable to read from reader. */ public static String safeReadFully(Reader reader) throws IOException { String ret = readFully(reader); return ret == null ? "" : ret; } /** * 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. * @return the local file system path for the file. * @since Ant 1.6 */ public String fromURI(String uri) { synchronized (cacheFromUriLock) { if (uri.equals(cacheFromUriRequest)) { return cacheFromUriResponse; } String path = Locator.fromURI(uri); String ret = isAbsolutePath(path) ? normalize(path).getAbsolutePath() : path; cacheFromUriRequest = uri; cacheFromUriResponse = ret; return ret; } } /** * Compares two filenames. * * <p>Unlike java.io.File#equals this method will try to compare * the absolute paths and "normalize" the filenames * before comparing them.</p> * * @param f1 the file whose name is to be compared. * @param f2 the other file whose name is to be compared. * * @return true if the file are for the same file. * * @since Ant 1.5.3 */ public boolean fileNameEquals(File f1, File f2) { return normalize(f1.getAbsolutePath()).getAbsolutePath().equals( normalize(f2.getAbsolutePath()).getAbsolutePath()); } /** * Renames a file, even if that involves crossing file system boundaries. * * <p>This will remove <code>to</code> (if it exists), ensure that * <code>to</code>'s parent directory exists and move * <code>from</code>, which involves deleting <code>from</code> as * well.</p> * * @param from the file to move. * @param to the new file name. * * @throws IOException if anything bad happens during this * process. Note that <code>to</code> may have been deleted * already when this happens. * * @since Ant 1.6 */ public void rename(File from, File to) throws IOException { from = normalize(from.getAbsolutePath()).getCanonicalFile(); to = normalize(to.getAbsolutePath()); if (!from.exists()) { System.err.println("Cannot rename nonexistent file " + from); return; } if (from.equals(to)) { System.err.println("Rename of " + from + " to " + to + " is a no-op."); return; } if (to.exists() && !(from.equals(to.getCanonicalFile()) || to.delete())) { throw new IOException("Failed to delete " + to + " while trying to rename " + from); } File parent = to.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { throw new IOException("Failed to create directory " + parent + " while trying to rename " + from); } if (!from.renameTo(to)) { copyFile(from, to); if (!from.delete()) { throw new IOException("Failed to delete " + from + " while trying to rename it."); } } } /** * Get the granularity of file timestamps. The choice is made based on OS, which is * incorrect--it should really be by filesystem. We do not have an easy way to probe for file * systems, however, so this heuristic gives us a decent default. * * @return the difference, in milliseconds, which two file timestamps must have in order for the * two files to be considered to have different timestamps. */ public long getFileTimestampGranularity() { if (ON_WIN9X) { return FAT_FILE_TIMESTAMP_GRANULARITY; } if (ON_WINDOWS) { return NTFS_FILE_TIMESTAMP_GRANULARITY; } if (ON_DOS) { return FAT_FILE_TIMESTAMP_GRANULARITY; } return UNIX_FILE_TIMESTAMP_GRANULARITY; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -