Which of the following method automatically creates a new empty file named by this abstract pathname?
line wrap: on Show line source /* * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.net.URI; import java.net.URL; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.List; import java.util.ArrayList; import java.security.AccessController; import java.security.SecureRandom; import java.nio.file.Path; import java.nio.file.FileSystems; import sun.security.action.GetPropertyAction; /** * An abstract representation of file and directory pathnames. * ** * @param writable * If true , sets the access permission to allow write
* operations; if false to disallow write operations
*
* @return true if and only if the operation succeeded. The
* operation will fail if the user does not have permission to
* change the access permissions of this abstract pathname.
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.6
*/
public boolean setWritable(boolean writable) {
return setWritable(writable, true);
}
/**
* Sets the owner's or everybody's read permission for this abstract
* pathname. On some platforms it may be possible to start the Java virtual
* machine with special privileges that allow it to read files that are
* marked as unreadable.
*
* The {@link java.nio.file.Files} class defines methods that operate on * file attributes including file permissions. This may be used when finer * manipulation of file permissions is required. * * @param readable * Iftrue , sets the access permission to allow read
* operations; if false to disallow read operations
*
* @param ownerOnly
* If true , the read permission applies only to the
* owner's read permission; otherwise, it applies to everybody. If
* the underlying file system can not distinguish the owner's read
* permission from that of others, then the permission will apply to
* everybody, regardless of this value.
*
* @return true if and only if the operation succeeded. The
* operation will fail if the user does not have permission to
* change the access permissions of this abstract pathname. If
* readable is false and the underlying
* file system does not implement a read permission, then the
* operation will fail.
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.6
*/
public boolean setReadable(boolean readable, boolean ownerOnly) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
}
/**
* A convenience method to set the owner's read permission for this abstract
* pathname. On some platforms it may be possible to start the Java virtual
* machine with special privileges that allow it to read files that that are
* marked as unreadable.
*
* An invocation of this method of the form file.setReadable(arg) * behaves in exactly the same way as the invocation * * * file.setReadable(arg, true) * * @param readable * Iftrue , sets the access permission to allow read
* operations; if false to disallow read operations
*
* @return true if and only if the operation succeeded. The
* operation will fail if the user does not have permission to
* change the access permissions of this abstract pathname. If
* readable is false and the underlying
* file system does not implement a read permission, then the
* operation will fail.
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.6
*/
public boolean setReadable(boolean readable) {
return setReadable(readable, true);
}
/**
* Sets the owner's or everybody's execute permission for this abstract
* pathname. On some platforms it may be possible to start the Java virtual
* machine with special privileges that allow it to execute files that are
* not marked executable.
*
* The {@link java.nio.file.Files} class defines methods that operate on * file attributes including file permissions. This may be used when finer * manipulation of file permissions is required. * * @param executable * Iftrue , sets the access permission to allow execute
* operations; if false to disallow execute operations
*
* @param ownerOnly
* If true , the execute permission applies only to the
* owner's execute permission; otherwise, it applies to everybody.
* If the underlying file system can not distinguish the owner's
* execute permission from that of others, then the permission will
* apply to everybody, regardless of this value.
*
* @return true if and only if the operation succeeded. The
* operation will fail if the user does not have permission to
* change the access permissions of this abstract pathname. If
* executable is false and the underlying
* file system does not implement an execute permission, then the
* operation will fail.
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.6
*/
public boolean setExecutable(boolean executable, boolean ownerOnly) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
}
/**
* A convenience method to set the owner's execute permission for this
* abstract pathname. On some platforms it may be possible to start the Java
* virtual machine with special privileges that allow it to execute files
* that are not marked executable.
*
* An invocation of this method of the form file.setExcutable(arg) * behaves in exactly the same way as the invocation * * * file.setExecutable(arg, true) * * @param executable * Iftrue , sets the access permission to allow execute
* operations; if false to disallow execute operations
*
* @return true if and only if the operation succeeded. The
* operation will fail if the user does not have permission to
* change the access permissions of this abstract pathname. If
* executable is false and the underlying
* file system does not implement an execute permission, then the
* operation will fail.
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.6
*/
public boolean setExecutable(boolean executable) {
return setExecutable(executable, true);
}
/**
* Tests whether the application can execute the file denoted by this
* abstract pathname. On some platforms it may be possible to start the
* Java virtual machine with special privileges that allow it to execute
* files that are not marked executable. Consequently this method may return
* {@code true} even though the file does not have execute permissions.
*
* @return true if and only if the abstract pathname exists
* and the application is allowed to execute the file
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkExec(java.lang.String)}
* method denies execute access to the file
*
* @since 1.6
*/
public boolean canExecute() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkExec(path);
}
if (isInvalid()) {
return false;
}
return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
}
/* -- Filesystem interface -- */
/**
* List the available filesystem roots.
*
* A particular Java platform may support zero or more * hierarchically-organized file systems. Each file system has a * {@code root} directory from which all other files in that file system * can be reached. Windows platforms, for example, have a root directory * for each active drive; UNIX platforms have a single root directory, * namely {@code "/"}. The set of available filesystem roots is affected * by various system-level operations such as the insertion or ejection of * removable media and the disconnecting or unmounting of physical or * virtual disk drives. * *This method returns an array of {@code File} objects that denote the * root directories of the available filesystem roots. It is guaranteed * that the canonical pathname of any file physically present on the local * machine will begin with one of the roots returned by this method. * *The canonical pathname of a file that resides on some other machine * and is accessed via a remote-filesystem protocol such as SMB or NFS may * or may not begin with one of the roots returned by this method. If the * pathname of a remote file is syntactically indistinguishable from the * pathname of a local file then it will begin with one of the roots * returned by this method. Thus, for example, {@code File} objects * denoting the root directories of the mapped network drives of a Windows * platform will be returned by this method, while {@code File} objects * containing UNC pathnames will not be returned by this method. * *Unlike most methods in this class, this method does not throw * security exceptions. If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to a * particular root directory, then that directory will not appear in the * result. * * @return An array of {@code File} objects denoting the available * filesystem roots, or {@code null} if the set of roots could not * be determined. The array will be empty if there are no * filesystem roots. * * @since 1.2 * @see java.nio.file.FileStore */ public static File[] listRoots() { return fs.listRoots(); } /* -- Disk usage -- */ /** * Returns the size of the partition named by this * abstract pathname. * * @return The size, in bytes, of the partition or 0L if this * abstract pathname does not name a partition * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}("getFileSystemAttributes") * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getTotalSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_TOTAL); } /** * Returns the number of unallocated bytes in the partition * href="#partName">named by this abstract path name. * *The returned number of unallocated bytes is a hint, but not * a guarantee, that it is possible to use most or any of these * bytes. The number of unallocated bytes is most likely to be * accurate immediately after this call. It is likely to be made * inaccurate by any external I/O operations including those made * on the system outside of this virtual machine. This method * makes no guarantee that write operations to this file system * will succeed. * * @return The number of unallocated bytes on the partition or 0L * if the abstract pathname does not name a partition. This * value will be less than or equal to the total file system size * returned by {@link #getTotalSpace}. * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}("getFileSystemAttributes") * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getFreeSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_FREE); } /** * Returns the number of bytes available to this virtual machine on the * partition named by this abstract pathname. When * possible, this method checks for write permissions and other operating * system restrictions and will therefore usually provide a more accurate * estimate of how much new data can actually be written than {@link * #getFreeSpace}. * *The returned number of available bytes is a hint, but not a * guarantee, that it is possible to use most or any of these bytes. The * number of unallocated bytes is most likely to be accurate immediately * after this call. It is likely to be made inaccurate by any external * I/O operations including those made on the system outside of this * virtual machine. This method makes no guarantee that write operations * to this file system will succeed. * * @return The number of available bytes on the partition or 0L * if the abstract pathname does not name a partition. On * systems where this information is not available, this method * will be equivalent to a call to {@link #getFreeSpace}. * * @throws SecurityException * If a security manager has been installed and it denies * {@link RuntimePermission}("getFileSystemAttributes") * or its {@link SecurityManager#checkRead(String)} method denies * read access to the file named by this abstract pathname * * @since 1.6 */ public long getUsableSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_USABLE); } /* -- Temporary files -- */ private static class TempDirectory { private TempDirectory() { } // temporary directory location private static final File tmpdir = new File(AccessController .doPrivileged(new GetPropertyAction("java.io.tmpdir"))); static File location() { return tmpdir; } // file name generation private static final SecureRandom random = new SecureRandom(); static File generateFile(String prefix, String suffix, File dir) throws IOException { long n = random.nextLong(); if (n == Long.MIN_VALUE) { n = 0; // corner case } else { n = Math.abs(n); } // Use only the file name from the supplied prefix prefix = (new File(prefix)).getName(); String name = prefix + Long.toString(n) + suffix; File f = new File(dir, name); if (!name.equals(f.getName()) || f.isInvalid()) { if (System.getSecurityManager() != null) throw new IOException("Unable to create temporary file"); else throw new IOException("Unable to create temporary file, " + f); } return f; } } /** *Creates a new empty file in the specified directory, using the * given prefix and suffix strings to generate its name. If this method * returns successfully then it is guaranteed that: * *{@link #deleteOnExit} method.
*
* The "hjb" or "mail" . The
* suffix argument may be null , in which case the
* suffix ".tmp" will be used.
*
* To create the new file, the prefix and the suffix may first be * adjusted to fit the limitations of the underlying platform. If the * prefix is too long then it will be truncated, but its first three * characters will always be preserved. If the suffix is too long then it * too will be truncated, but if it begins with a period character * ('.' ) then the period and the first three characters
* following it will always be preserved. Once these adjustments have been
* made the name of the new file will be generated by concatenating the
* prefix, five or more internally-generated characters, and the suffix.
*
* If the java.io.tmpdir . On UNIX systems the default value of this
* property is typically "/tmp" or "/var/tmp" ; on
* Microsoft Windows systems it is typically "C:\\WINNT\\TEMP" . A different
* value may be given to this system property when the Java virtual machine
* is invoked, but programmatic changes to this property are not guaranteed
* to have any effect upon the temporary directory used by this method.
*
* @param prefix The prefix string to be used in generating the file's
* name; must be at least three characters long
*
* @param suffix The suffix string to be used in generating the file's
* name; may be null , in which case the
* suffix ".tmp" will be used
*
* @param directory The directory in which the file is to be created, or
* null if the default temporary-file
* directory is to be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException
* If the prefix argument contains fewer than three
* characters
*
* @throws IOException If a file could not be created
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not allow a file to be created
*
* @since 1.2
*/
public static File createTempFile(String prefix, String suffix,
File directory)
throws IOException
{
if (prefix.length() < 3)
throw new IllegalArgumentException("Prefix string too short");
if (suffix == null)
suffix = ".tmp";
File tmpdir = (directory != null) ? directory
: TempDirectory.location();
SecurityManager sm = System.getSecurityManager();
File f;
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
if (sm != null) {
try {
sm.checkWrite(f.getPath());
} catch (SecurityException se) {
// don't reveal temporary directory location
if (directory == null)
throw new SecurityException("Unable to create temporary file");
throw se;
}
}
} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
if (!fs.createFileExclusively(f.getPath()))
throw new IOException("Unable to create temporary file");
return f;
}
/**
* Creates an empty file in the default temporary-file directory, using
* the given prefix and suffix to generate its name. Invoking this method
* is equivalent to invoking {@link #createTempFile(java.lang.String,
* java.lang.String, java.io.File)
* createTempFile(prefix, suffix, null)}.
*
* The {@link * java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[]) * Files.createTempFile} method provides an alternative method to create an * empty file in the temporary-file directory. Files created by that method * may have more restrictive access permissions to files created by this * method and so may be more suited to security-sensitive applications. * * @param prefix The prefix string to be used in generating the file's * name; must be at least three characters long * * @param suffix The suffix string to be used in generating the file's * name; may benull , in which case the
* suffix ".tmp" will be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException
* If the prefix argument contains fewer than three
* characters
*
* @throws IOException If a file could not be created
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not allow a file to be created
*
* @since 1.2
* @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
*/
public static File createTempFile(String prefix, String suffix)
throws IOException
{
return createTempFile(prefix, suffix, null);
}
/* -- Basic infrastructure -- */
/**
* Compares two abstract pathnames lexicographically. The ordering
* defined by this method depends upon the underlying system. On UNIX
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
* systems it is not.
*
* @param pathname The abstract pathname to be compared to this abstract
* pathname
*
* @return Zero if the argument is equal to this abstract pathname, a
* value less than zero if this abstract pathname is
* lexicographically less than the argument, or a value greater
* than zero if this abstract pathname is lexicographically
* greater than the argument
*
* @since 1.2
*/
public int compareTo(File pathname) {
return fs.compare(this, pathname);
}
/**
* Tests this abstract pathname for equality with the given object.
* Returns true if and only if the argument is not
* null and is an abstract pathname that denotes the same file
* or directory as this abstract pathname. Whether or not two abstract
* pathnames are equal depends upon the underlying system. On UNIX
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
* systems it is not.
*
* @param obj The object to be compared with this abstract pathname
*
* @return true if and only if the objects are the same;
* false otherwise
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof File)) {
return compareTo((File)obj) == 0;
}
return false;
}
/**
* Computes a hash code for this abstract pathname. Because equality of
* abstract pathnames is inherently system-dependent, so is the computation
* of their hash codes. On UNIX systems, the hash code of an abstract
* pathname is equal to the exclusive or of the hash code
* of its pathname string and the decimal value
* 1234321 . On Microsoft Windows systems, the hash
* code is equal to the exclusive or of the hash code of
* its pathname string converted to lower case and the decimal
* value 1234321 . Locale is not taken into account on
* lowercasing the pathname string.
*
* @return A hash code for this abstract pathname
*/
public int hashCode() {
return fs.hashCode(this);
}
/**
* Returns the pathname string of this abstract pathname. This is just the
* string returned by the {@link #getPath} method.
*
* @return The string form of this abstract pathname
*/
public String toString() {
return getPath();
}
/**
* WriteObject is called to save this filename.
* The separator character is saved also so it can be replaced
* in case the path is reconstituted on a different host type.
*
* @serialData Default fields followed by separator character.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
s.writeChar(separatorChar); // Add the separator character
}
/**
* readObject is called to restore this filename.
* The original separator character is read. If it is different
* than the separator character on this system, then the old separator
* is replaced by the local separator.
*/
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = s.readFields();
String pathField = (String)fields.get("path", null);
char sep = s.readChar(); // read the previous separator char
if (sep != separatorChar)
pathField = pathField.replace(sep, separatorChar);
String path = fs.normalize(pathField);
UNSAFE.putObject(this, PATH_OFFSET, path);
UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));
}
private static final long PATH_OFFSET;
private static final long PREFIX_LENGTH_OFFSET;
private static final sun.misc.Unsafe UNSAFE;
static {
try {
sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
PATH_OFFSET = unsafe.objectFieldOffset(
File.class.getDeclaredField("path"));
PREFIX_LENGTH_OFFSET = unsafe.objectFieldOffset(
File.class.getDeclaredField("prefixLength"));
UNSAFE = unsafe;
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = 301077366599181567L;
// -- Integration with java.nio.file --
private volatile transient Path filePath;
/**
* Returns a {@link Path java.nio.file.Path} object constructed from the
* this abstract path. The resulting {@code Path} is associated with the
* {@link java.nio.file.FileSystems#getDefault default-filesystem}.
*
* The first invocation of this method works as if invoking it were * equivalent to evaluating the expression: ** {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link * java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}()); * * Subsequent invocations of this method return the same {@code Path}. * * If this abstract pathname is the empty abstract pathname then this * method returns a {@code Path} that may be used to access the current * user directory. * * @return a {@code Path} constructed from this abstract path * * @throws java.nio.file.InvalidPathException * if a {@code Path} object cannot be constructed from the abstract * path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath}) * * @since 1.7 * @see Path#toFile */ public Path toPath() { Path result = filePath; if (result == null) { synchronized (this) { result = filePath; if (result == null) { result = FileSystems.getDefault().getPath(path); filePath = result; } } } return result; } }What methods deletes the file or directory denoted by this abstract pathname?delete() method of java.io package deletes the file or directory denoted by the abstract pathname. It can delete only empty directories and does not throw any exceptions.
What is an abstract pathname?An abstract pathname has two components: An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Microsoft Windows UNC pathname, and. A sequence of zero or more string names.
Which of the following method is used to check whether the file denoted by the pathname is a directory?The isDirectory method can be used to test if the file denoted by the provided name is a directory, while the isFile method can be used to test if the file denoted by the provided name is a file. And, we can use the exists method to test whether a directory or file already exists on the system.
What does the files list () method in Java do?list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.
|