Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2007 The Guava Authors
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    * http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package com.google.common.io;
  
  import static com.google.common.base.Preconditions.checkArgument;
  import static com.google.common.base.Preconditions.checkNotNull;
  import static com.google.common.io.FileWriteMode.APPEND;
  
  
  import java.io.Closeable;
  import java.io.File;
  import java.util.Arrays;
  import java.util.List;

Provides utility methods for working with files.

All method parameters must be non-null unless documented otherwise.

Author(s):
Chris Nokleberg
Colin Decker
Since:
1.0
  
  @Beta
  public final class Files {

  
Maximum loop count when creating temp directories.
  
    private static final int TEMP_DIR_ATTEMPTS = 10000;
  
    private Files() {}

  
Returns a buffered reader that reads from a file using the given character set.

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the buffered reader
  
    public static BufferedReader newReader(File fileCharset charset)
        throws FileNotFoundException {
      checkNotNull(file);
      checkNotNull(charset);
      return new BufferedReader(
          new InputStreamReader(new FileInputStream(file), charset));
    }

  
Returns a buffered writer that writes to a file using the given character set.

Parameters:
file the file to write to
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the buffered writer
  
   public static BufferedWriter newWriter(File fileCharset charset)
       throws FileNotFoundException {
     checkNotNull(file);
     checkNotNull(charset);
     return new BufferedWriter(
         new OutputStreamWriter(new FileOutputStream(file), charset));
   }

  
Returns a new ByteSource for reading bytes from the given file.

Since:
14.0
 
   public static ByteSource asByteSource(File file) {
     return new FileByteSource(file);
   }
 
   private static final class FileByteSource extends ByteSource {
 
     private final File file;
 
     private FileByteSource(File file) {
       this. = checkNotNull(file);
     }
 
     @Override
     public FileInputStream openStream() throws IOException {
       return new FileInputStream();
     }
 
     @Override
     public long size() throws IOException {
       if (!.isFile()) {
         throw new FileNotFoundException(.toString());
       }
       return .length();
     }
 
     @Override
     public byte[] read() throws IOException {
       long size = .length();
       // some special files may return size 0 but have content
       // read normally to be sure
       if (size == 0) {
         return super.read();
       }
 
       // can't initialize a large enough array
       // technically, this could probably be Integer.MAX_VALUE - 5
       if (size > .) {
         // OOME is what would be thrown if we tried to initialize the array
         throw new OutOfMemoryError("file is too large to fit in a byte array: "
             + size + " bytes");
       }
 
       // initialize the array to the current size of the file
       byte[] bytes = new byte[(intsize];
 
       Closer closer = Closer.create();
       try {
         InputStream in = closer.register(openStream());
         int off = 0;
         int read = 0;
 
         // read until we've read size bytes or reached EOF
         while (off < size
             && ((read = in.read(bytesoff, (intsize - off)) != -1)) {
           off += read;
         }
 
         if (off < size) {
           // encountered EOF early; truncate the result
           return Arrays.copyOf(bytesoff);
         }
 
         // otherwise, exactly size bytes were read
 
         int b = in.read(); // check for EOF
         if (b == -1) {
           // EOF; the file did not change size, so return the original array
           return bytes;
         }
 
         // the file got larger, so read the rest normally
         InternalByteArrayOutputStream out
             = new InternalByteArrayOutputStream();
         out.write(b); // write the byte we read when testing for EOF
         ByteStreams.copy(inout);
 
         byte[] result = new byte[bytes.length + out.size()];
         System.arraycopy(bytes, 0, result, 0, bytes.length);
         out.writeTo(resultbytes.length);
         return result;
       } catch (Throwable e) {
         throw closer.rethrow(e);
       } finally {
         closer.close();
       }
     }
 
     @Override
     public String toString() {
       return "Files.asByteSource(" +  + ")";
     }
   }

  
BAOS subclass for direct access to its internal buffer.
 
   private static final class InternalByteArrayOutputStream
       extends ByteArrayOutputStream {
    
Writes the contents of the internal buffer to the given array starting at the given offset. Assumes the array has space to hold count bytes.
 
     void writeTo(byte[] bint off) {
       System.arraycopy(, 0, boff);
     }
   }

  
Returns a new ByteSink for writing bytes to the given file. The given modes control how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When the APPEND mode is provided, writes will append to the end of the file without truncating it.

Since:
14.0
 
   public static ByteSink asByteSink(File fileFileWriteMode... modes) {
     return new FileByteSink(filemodes);
   }
 
   private static final class FileByteSink extends ByteSink {
 
     private final File file;
     private final ImmutableSet<FileWriteModemodes;
 
     private FileByteSink(File fileFileWriteMode... modes) {
       this. = checkNotNull(file);
       this. = ImmutableSet.copyOf(modes);
     }
 
     @Override
     public FileOutputStream openStream() throws IOException {
       return new FileOutputStream(.contains());
     }
 
     @Override
     public String toString() {
       return "Files.asByteSink(" +  + ", " +  + ")";
     }
   }

  
Returns a new CharSource for reading character data from the given file using the given character set.

Since:
14.0
 
   public static CharSource asCharSource(File fileCharset charset) {
     return asByteSource(file).asCharSource(charset);
   }

  
Returns a new CharSink for writing character data to the given file using the given character set. The given modes control how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When the APPEND mode is provided, writes will append to the end of the file without truncating it.

Since:
14.0
 
   public static CharSink asCharSink(File fileCharset charset,
       FileWriteMode... modes) {
     return asByteSink(filemodes).asCharSink(charset);
   }

  
Returns a factory that will supply instances of java.io.FileInputStream that read from a file.

Parameters:
file the file to read from
Returns:
the factory
 
       final File file) {
     return ByteStreams.asInputSupplier(asByteSource(file));
   }

  
Returns a factory that will supply instances of java.io.FileOutputStream that write to a file.

Parameters:
file the file to write to
Returns:
the factory
 
       File file) {
     return newOutputStreamSupplier(filefalse);
   }

  
Returns a factory that will supply instances of java.io.FileOutputStream that write to or append to a file.

Parameters:
file the file to write to
append if true, the encoded characters will be appended to the file; otherwise the file is overwritten
Returns:
the factory
 
       final File filefinal boolean append) {
     return ByteStreams.asOutputSupplier(asByteSink(filemodes(append)));
   }
 
   private static FileWriteMode[] modes(boolean append) {
     return append
         ? new FileWriteMode[]{ . }
         : new FileWriteMode[0];
   }

  
Returns a factory that will supply instances of java.io.InputStreamReader that read a file using the given character set.

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the factory
 
       Charset charset) {
     return CharStreams.asInputSupplier(asCharSource(filecharset));
   }

  
Returns a factory that will supply instances of java.io.OutputStreamWriter that write to a file using the given character set.

Parameters:
file the file to write to
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the factory
 
       Charset charset) {
     return newWriterSupplier(filecharsetfalse);
   }

  
Returns a factory that will supply instances of java.io.OutputStreamWriter that write to or append to a file using the given character set.

Parameters:
file the file to write to
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
append if true, the encoded characters will be appended to the file; otherwise the file is overwritten
Returns:
the factory
 
       Charset charsetboolean append) {
     return CharStreams.asOutputSupplier(asCharSink(filecharsetmodes(append)));
   }

  
Reads all bytes from a file into a byte array.

Parameters:
file the file to read from
Returns:
a byte array containing all the bytes from file
Throws:
java.lang.IllegalArgumentException if the file is bigger than the largest possible byte array (2^31 - 1)
java.io.IOException if an I/O error occurs
 
   public static byte[] toByteArray(File filethrows IOException {
     return asByteSource(file).read();
   }

  
Reads all characters from a file into a java.lang.String, using the given character set.

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
a string containing all the characters from the file
Throws:
java.io.IOException if an I/O error occurs
 
   public static String toString(File fileCharset charsetthrows IOException {
     return asCharSource(filecharset).read();
   }

  
Copies to a file all bytes from an java.io.InputStream supplied by a factory.

Parameters:
from the input factory
to the destination file
Throws:
java.io.IOException if an I/O error occurs
 
   public static void copy(InputSupplier<? extends InputStreamfromFile to)
       throws IOException {
     ByteStreams.asByteSource(from).copyTo(asByteSink(to));
   }

  
Overwrites a file with the contents of a byte array.

Parameters:
from the bytes to write
to the destination file
Throws:
java.io.IOException if an I/O error occurs
 
   public static void write(byte[] fromFile tothrows IOException {
     asByteSink(to).write(from);
   }

  
Copies all bytes from a file to an java.io.OutputStream supplied by a factory.

Parameters:
from the source file
to the output factory
Throws:
java.io.IOException if an I/O error occurs
 
   public static void copy(File fromOutputSupplier<? extends OutputStreamto)
       throws IOException {
     asByteSource(from).copyTo(ByteStreams.asByteSink(to));
   }

  
Copies all bytes from a file to an output stream.

Parameters:
from the source file
to the output stream
Throws:
java.io.IOException if an I/O error occurs
 
   public static void copy(File fromOutputStream tothrows IOException {
     asByteSource(from).copyTo(to);
   }

  
Copies all the bytes from one file to another.

Warning: If to represents an existing file, that file will be overwritten with the contents of from. If to and from refer to the same file, the contents of that file will be deleted.

Parameters:
from the source file
to the destination file
Throws:
java.io.IOException if an I/O error occurs
java.lang.IllegalArgumentException if from.equals(to)
 
   public static void copy(File fromFile tothrows IOException {
     checkArgument(!from.equals(to),
         "Source %s and destination %s must be different"fromto);
     asByteSource(from).copyTo(asByteSink(to));
   }

  
Copies to a file all characters from a java.lang.Readable and java.io.Closeable object supplied by a factory, using the given character set.

Parameters:
from the readable supplier
to the destination file
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Throws:
java.io.IOException if an I/O error occurs
 
   public static <R extends Readable & Closeablevoid copy(
       InputSupplier<R> fromFile toCharset charsetthrows IOException {
     CharStreams.asCharSource(from).copyTo(asCharSink(tocharset));
   }

  
Writes a character sequence (such as a string) to a file using the given character set.

Parameters:
from the character sequence to write
to the destination file
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Throws:
java.io.IOException if an I/O error occurs
 
   public static void write(CharSequence fromFile toCharset charset)
       throws IOException {
     asCharSink(tocharset).write(from);
   }

  
Appends a character sequence (such as a string) to a file using the given character set.

Parameters:
from the character sequence to append
to the destination file
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
Throws:
java.io.IOException if an I/O error occurs
 
   public static void append(CharSequence fromFile toCharset charset)
       throws IOException {
     write(fromtocharsettrue);
   }

  
Private helper method. Writes a character sequence to a file, optionally appending.

Parameters:
from the character sequence to append
to the destination file
charset the charset used to encode the output stream; see com.google.common.base.Charsets for helpful predefined constants
append true to append, false to overwrite
Throws:
java.io.IOException if an I/O error occurs
 
   private static void write(CharSequence fromFile toCharset charset,
       boolean appendthrows IOException {
     asCharSink(tocharsetmodes(append)).write(from);
   }

  
Copies all characters from a file to a java.lang.Appendable & java.io.Closeable object supplied by a factory, using the given character set.

Parameters:
from the source file
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
to the appendable supplier
Throws:
java.io.IOException if an I/O error occurs
 
   public static <W extends Appendable & Closeablevoid copy(File from,
       Charset charsetOutputSupplier<W> tothrows IOException {
     asCharSource(fromcharset).copyTo(CharStreams.asCharSink(to));
   }

  
Copies all characters from a file to an appendable object, using the given character set.

Parameters:
from the source file
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
to the appendable object
Throws:
java.io.IOException if an I/O error occurs
 
   public static void copy(File fromCharset charsetAppendable to)
       throws IOException {
     asCharSource(fromcharset).copyTo(to);
   }

  
Returns true if the files contains the same bytes.

Throws:
java.io.IOException if an I/O error occurs
 
   public static boolean equal(File file1File file2throws IOException {
     checkNotNull(file1);
     checkNotNull(file2);
     if (file1 == file2 || file1.equals(file2)) {
       return true;
     }
 
     /*
      * Some operating systems may return zero as the length for files
      * denoting system-dependent entities such as devices or pipes, in
      * which case we must fall back on comparing the bytes directly.
      */
     long len1 = file1.length();
     long len2 = file2.length();
     if (len1 != 0 && len2 != 0 && len1 != len2) {
       return false;
     }
     return asByteSource(file1).contentEquals(asByteSource(file2));
   }

  
Atomically creates a new directory somewhere beneath the system's temporary directory (as defined by the java.io.tmpdir system property), and returns its name.

Use this method instead of java.io.File.createTempFile(java.lang.String,java.lang.String) when you wish to create a directory, not a regular file. A common pitfall is to call createTempFile, delete the file and create a directory in its place, but this leads a race condition which can be exploited to create security vulnerabilities, especially when executable files are to be written into the directory.

This method assumes that the temporary volume is writable, has free inodes and free blocks, and that it will not be called thousands of times per second.

Returns:
the newly-created directory
Throws:
java.lang.IllegalStateException if the directory could not be created
 
   public static File createTempDir() {
     File baseDir = new File(System.getProperty("java.io.tmpdir"));
     String baseName = System.currentTimeMillis() + "-";
 
     for (int counter = 0; counter < counter++) {
       File tempDir = new File(baseDirbaseName + counter);
       if (tempDir.mkdir()) {
         return tempDir;
       }
     }
     throw new IllegalStateException("Failed to create directory within "
         +  + " attempts (tried "
         + baseName + "0 to " + baseName + ( - 1) + ')');
   }

  
Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.

Parameters:
file the file to create or update
Throws:
java.io.IOException if an I/O error occurs
 
   public static void touch(File filethrows IOException {
     checkNotNull(file);
     if (!file.createNewFile()
         && !file.setLastModified(System.currentTimeMillis())) {
       throw new IOException("Unable to update modification time of " + file);
     }
   }

  
Creates any necessary but nonexistent parent directories of the specified file. Note that if this operation fails it may have succeeded in creating some (but not all) of the necessary parent directories.

Throws:
java.io.IOException if an I/O error occurs, or if any necessary but nonexistent parent directories of the specified file could not be created.
Since:
4.0
 
   public static void createParentDirs(File filethrows IOException {
     checkNotNull(file);
     File parent = file.getCanonicalFile().getParentFile();
     if (parent == null) {
       /*
        * The given directory is a filesystem root. All zero of its ancestors
        * exist. This doesn't mean that the root itself exists -- consider x:\ on
        * a Windows machine without such a drive -- or even that the caller can
        * create it, but this method makes no such guarantees even for non-root
        * files.
        */
       return;
     }
     parent.mkdirs();
     if (!parent.isDirectory()) {
       throw new IOException("Unable to create parent directories of " + file);
     }
   }

  
Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.

Parameters:
from the source file
to the destination file
Throws:
java.io.IOException if an I/O error occurs
java.lang.IllegalArgumentException if from.equals(to)
 
   public static void move(File fromFile tothrows IOException {
     checkNotNull(from);
     checkNotNull(to);
     checkArgument(!from.equals(to),
         "Source %s and destination %s must be different"fromto);
 
     if (!from.renameTo(to)) {
       copy(fromto);
       if (!from.delete()) {
         if (!to.delete()) {
           throw new IOException("Unable to delete " + to);
         }
         throw new IOException("Unable to delete " + from);
       }
     }
   }

  
Reads the first line from a file. The line does not include line-termination characters, but does include other leading and trailing whitespace.

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
the first line, or null if the file is empty
Throws:
java.io.IOException if an I/O error occurs
 
   public static String readFirstLine(File fileCharset charset)
       throws IOException {
     return asCharSource(filecharset).readFirstLine();
   }

  
Reads all of the lines from a file. The lines do not include line-termination characters, but do include other leading and trailing whitespace.

This method returns a mutable List. For an ImmutableList, use Files.asCharSource(file, charset).readLines().

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
Returns:
a mutable java.util.List containing all the lines
Throws:
java.io.IOException if an I/O error occurs
 
   public static List<StringreadLines(File fileCharset charset)
       throws IOException {
     // don't use asCharSource(file, charset).readLines() because that returns
     // an immutable list, which would change the behavior of this method
     return readLines(filecharsetnew LineProcessor<List<String>>() {
       final List<Stringresult = Lists.newArrayList();
 
       @Override
       public boolean processLine(String line) {
         .add(line);
         return true;
       }
 
       @Override
       public List<StringgetResult() {
         return ;
       }
     });
   }

  
Streams lines from a java.io.File, stopping when our callback returns false, or we have read all of the lines.

Parameters:
file the file to read from
charset the charset used to decode the input stream; see com.google.common.base.Charsets for helpful predefined constants
callback the LineProcessor to use to handle the lines
Returns:
the output of processing the lines
Throws:
java.io.IOException if an I/O error occurs
 
   public static <T> T readLines(File fileCharset charset,
       LineProcessor<T> callbackthrows IOException {
     return CharStreams.readLines(newReaderSupplier(filecharset), callback);
   }

  
Process the bytes of a file.

(If this seems too complicated, maybe you're looking for toByteArray(java.io.File).)

Parameters:
file the file to read
processor the object to which the bytes of the file are passed.
Returns:
the result of the byte processor
Throws:
java.io.IOException if an I/O error occurs
 
   public static <T> T readBytes(File fileByteProcessor<T> processor)
       throws IOException {
     return ByteStreams.readBytes(newInputStreamSupplier(file), processor);
   }

  
Computes the hash code of the file using hashFunction.

Parameters:
file the file to read
hashFunction the hash function to use to hash the data
Returns:
the com.google.common.hash.HashCode of all of the bytes in the file
Throws:
java.io.IOException if an I/O error occurs
Since:
12.0
 
   public static HashCode hash(File fileHashFunction hashFunction)
       throws IOException {
     return asByteSource(file).hash(hashFunction);
   }

  
Fully maps a file read-only in to memory as per java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long).

Files are mapped from offset 0 to its length.

This only works for files <= java.lang.Integer.MAX_VALUE bytes.

Parameters:
file the file to map
Returns:
a read-only buffer reflecting file
Throws:
java.io.FileNotFoundException if the file does not exist
java.io.IOException if an I/O error occurs
Since:
2.0
See also:
java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long)
 
   public static MappedByteBuffer map(File filethrows IOException {
     checkNotNull(file);
     return map(file.);
   }

  
Fully maps a file in to memory as per java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long) using the requested java.nio.channels.FileChannel.MapMode.

Files are mapped from offset 0 to its length.

This only works for files <= java.lang.Integer.MAX_VALUE bytes.

Parameters:
file the file to map
mode the mode to use when mapping file
Returns:
a buffer reflecting file
Throws:
java.io.FileNotFoundException if the file does not exist
java.io.IOException if an I/O error occurs
Since:
2.0
See also:
java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long)
 
   public static MappedByteBuffer map(File fileMapMode mode)
       throws IOException {
     checkNotNull(file);
     checkNotNull(mode);
     if (!file.exists()) {
       throw new FileNotFoundException(file.toString());
     }
     return map(filemodefile.length());
   }

  
Maps a file in to memory as per java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long) using the requested java.nio.channels.FileChannel.MapMode.

Files are mapped from offset 0 to size.

If the mode is java.nio.channels.FileChannel.MapMode.READ_WRITE and the file does not exist, it will be created with the requested size. Thus this method is useful for creating memory mapped files which do not yet exist.

This only works for files <= java.lang.Integer.MAX_VALUE bytes.

Parameters:
file the file to map
mode the mode to use when mapping file
Returns:
a buffer reflecting file
Throws:
java.io.IOException if an I/O error occurs
Since:
2.0
See also:
java.nio.channels.FileChannel.map(java.nio.channels.FileChannel.MapMode,long,long)
 
   public static MappedByteBuffer map(File fileMapMode modelong size)
       throws FileNotFoundExceptionIOException {
     checkNotNull(file);
     checkNotNull(mode);
 
     Closer closer = Closer.create();
     try {
       RandomAccessFile raf = closer.register(
           new RandomAccessFile(filemode == . ? "r" : "rw"));
       return map(rafmodesize);
     } catch (Throwable e) {
       throw closer.rethrow(e);
     } finally {
       closer.close();
     }
   }
 
   private static MappedByteBuffer map(RandomAccessFile rafMapMode mode,
       long sizethrows IOException {
     Closer closer = Closer.create();
     try {
       FileChannel channel = closer.register(raf.getChannel());
       return channel.map(mode, 0, size);
     } catch (Throwable e) {
       throw closer.rethrow(e);
     } finally {
       closer.close();
     }
   }

  
Returns the lexically cleaned form of the path name, usually (but not always) equivalent to the original. The following heuristics are used:
  • empty string becomes .
  • . stays as .
  • fold out ./
  • fold out ../ when possible
  • collapse multiple slashes
  • delete trailing slashes (unless the path is just "/")

These heuristics do not always match the behavior of the filesystem. In particular, consider the path a/../b, which simplifyPath will change to b. If a is a symlink to x, a/../b may refer to a sibling of x, rather than the sibling of a referred to by b.

Since:
11.0
 
   public static String simplifyPath(String pathname) {
     checkNotNull(pathname);
     if (pathname.length() == 0) {
       return ".";
     }
 
     // split the path apart
     Iterable<Stringcomponents =
         Splitter.on('/').omitEmptyStrings().split(pathname);
     List<Stringpath = new ArrayList<String>();
 
     // resolve ., .., and //
     for (String component : components) {
       if (component.equals(".")) {
         continue;
       } else if (component.equals("..")) {
         if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
           path.remove(path.size() - 1);
         } else {
           path.add("..");
         }
       } else {
         path.add(component);
       }
     }
 
     // put it back together
     String result = Joiner.on('/').join(path);
     if (pathname.charAt(0) == '/') {
       result = "/" + result;
     }
 
     while (result.startsWith("/../")) {
       result = result.substring(3);
     }
     if (result.equals("/..")) {
       result = "/";
     } else if ("".equals(result)) {
       result = ".";
     }
 
     return result;
   }

  
Returns the file extension for the given file name, or the empty string if the file has no extension. The result does not include the '.'.

Since:
11.0
 
   public static String getFileExtension(String fullName) {
     checkNotNull(fullName);
     String fileName = new File(fullName).getName();
     int dotIndex = fileName.lastIndexOf('.');
     return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
   }

  
Returns the file name without its file extension or path. This is similar to the basename unix command. The result does not include the '.'.

Parameters:
file The name of the file to trim the extension from. This can be either a fully qualified file name (including a path) or just a file name.
Returns:
The file name without its path or extension.
Since:
14.0
 
   public static String getNameWithoutExtension(String file) {
     checkNotNull(file);
     String fileName = new File(file).getName();
     int dotIndex = fileName.lastIndexOf('.');
     return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
   }

  
Returns a com.google.common.collect.TreeTraverser instance for java.io.File trees.

Warning: File provides no support for symbolic links, and as such there is no way to ensure that a symbolic link to a directory is not followed when traversing the tree. In this case, iterables created by this traverser could contain files that are outside of the given directory or even be infinite if there is a symbolic link loop.

Since:
15.0
 
   public static TreeTraverser<FilefileTreeTraverser() {
     return ;
   }
 
   private static final TreeTraverser<FileFILE_TREE_TRAVERSER = new TreeTraverser<File>() {
     @Override
     public Iterable<Filechildren(File file) {
       // check isDirectory() just because it may be faster than listFiles() on a non-directory
       if (file.isDirectory()) {
         File[] files = file.listFiles();
         if (files != null) {
           return Collections.unmodifiableList(Arrays.asList(files));
         }
       }
      return Collections.emptyList();
    }
    @Override
    public String toString() {
      return "Files.fileTreeTraverser()";
    }
  };

  
Returns a predicate that returns the result of java.io.File.isDirectory() on input files.

Since:
15.0
  public static Predicate<FileisDirectory() {
  }

  
Returns a predicate that returns the result of java.io.File.isFile() on input files.

Since:
15.0
  public static Predicate<FileisFile() {
    return .;
  }
  private enum FilePredicate implements Predicate<File> {
    IS_DIRECTORY {
      @Override
      public boolean apply(File file) {
        return file.isDirectory();
      }
      @Override
      public String toString() {
        return "Files.isDirectory()";
      }
    },
    IS_FILE {
      @Override
      public boolean apply(File file) {
        return file.isFile();
      }
      @Override
      public String toString() {
        return "Files.isFile()";
      }
    };
  }
New to GrepCode? Check out our FAQ X