Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
android/guava/src/com/google/common/io/Files.java
### 代码内容：
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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Provides utility methods for working with {@linkplain File files}.
 *
 *
{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
 * JDK's {@link java.nio.file.Files} class.
 *
 * @author Chris Nokleberg
 * @author Colin Decker
 * @since 1.0
 */
@GwtIncompatible
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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered reader
   */
  @Beta
  public static BufferedReader newReader(File file, Charset 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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
   * java.nio.file.OpenOption...)}.
   *
   * @param file the file to write to
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered writer
   */
  @Beta
  public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
    checkNotNull(file);
    checkNotNull(charset);
    return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
  }

  /**
   * Returns a new {@link 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.file = checkNotNull(file);
    }

    @Override
    public FileInputStream openStream() throws IOException {
      return new FileInputStream(file);
    }

    @Override
    public Optional<Long> sizeIfKnown() {
      if (file.isFile()) {
        return Optional.of(file.length());
      } else {
        return Optional.absent();
      }
    }

    @Override
    public long size() throws IOException {
      if (!file.isFile()) {
        throw new FileNotFoundException(file.toString());
      }
      return file.length();
    }

    @Override
    public byte[] read() throws IOException {
      Closer closer = Closer.create();
      try {
        FileInputStream in = closer.register(openStream());
        return ByteStreams.toByteArray(in, in.getChannel().size());
      } catch (Throwable e) {
        throw closer.rethrow(e);
      } finally {
        closer.close();
      }
    }

    @Override
    public String toString() {
      return "Files.asByteSource(" + file + ")";
    }
  }

  /**
   * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
   * control how the file is opened for writing. When no mode is provided, the file will be
   * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
   * will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static ByteSink asByteSink(File file, FileWriteMode... modes) {
    return new FileByteSink(file, modes);
  }

  private static final class FileByteSink extends ByteSink {

    private final File file;
    private final ImmutableSet<FileWriteMode> modes;

    private FileByteSink(File file, FileWriteMode... modes) {
      this.file = checkNotNull(file);
      this.modes = ImmutableSet.copyOf(modes);
    }

    @Override
    public FileOutputStream openStream() throws IOException {
      return new FileOutputStream(file, modes.contains(APPEND));
    }

    @Override
    public String toString() {
      return "Files.asByteSink(" + file + ", " + modes + ")";
    }
  }

  /**
   * Returns a new {@link CharSource} for reading character data from the given file using the given
   * character set.
   *
   * @since 14.0
   */
  public static CharSource asCharSource(File file, Charset charset) {
    return asByteSource(file).asCharSource(charset);
  }

  /**
   * Returns a new {@link CharSink} for writing character data to the given file using the given
   * character set. The given {@code modes} control how the file is opened for writing. When no mode
   * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
   * APPEND} mode is provided, writes will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
    return asByteSink(file, modes).asCharSink(charset);
  }

  /**
   * Reads all bytes from a file into a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#readAllBytes}.
   *
   * @param file the file to read from
   * @return a byte array containing all the bytes from file
   * @throws IllegalArgumentException if the file is bigger than the largest possible byte array
   *     (2^31 - 1)
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static byte[] toByteArray(File file) throws IOException {
    return asByteSource(file).read();
  }

  /**
   * Reads all characters from a file into a {@link String}, using the given character set.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a string containing all the characters from the file
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  public static String toString(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).read();
  }

  /**
   * Overwrites a file with the contents of a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
   *
   * @param from the bytes to write
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void write(byte[] from, File to) throws IOException {
    asByteSink(to).write(from);
  }

  /**
   * Writes a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to write
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  public static void write(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset).write(from);
  }

  /**
   * Copies all bytes from a file to an output stream.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
   *
   * @param from the source file
   * @param to the output stream
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void copy(File from, OutputStream to) throws IOException {
    asByteSource(from).copyTo(to);
  }

  /**
   * Copies all the bytes from one file to another.
   *
   *
Copying is not an atomic operation - in the case of an I/O error, power loss, process
   * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
   * need to guard against those conditions, you should employ other file-level synchronization.
   *
   *
Warning: If {@code to} represents an existing file, that file will be overwritten
   * with the contents of {@code from}. If {@code to} and {@code from} refer to the same
   * file, the contents of that file will be deleted.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

  /**
   * Copies all characters from a file to an appendable object, using the given character set.
   *
   * @param from the source file
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param to the appendable object
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
   *     be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static void copy(File from, Charset charset, Appendable to) throws IOException {
    asCharSource(from, charset).copyTo(to);
  }

  /**
   * Appends a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to append
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
   *     method is scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static void append(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset, FileWriteMode.APPEND).write(from);
  }

  /**
   * Returns true if the given files exist, are not directories, and contain the same bytes.
   *
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static boolean equal(File file1, File file2) throws 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 {@code java.io.tmpdir} system property), and returns its name.
   *
   *
Use this method instead of {@link File#createTempFile(String, String)} when you wish to
   * create a directory, not a regular file. A common pitfall is to call {@code 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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#createTempDirectory}.
   *
   * @return the newly-created directory
   * @throws IllegalStateException if the directory could not be created
   */
  @Beta
  public static File createTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    @SuppressWarnings("GoodTime") // reading system time without TimeSource
    String baseName = System.currentTimeMillis() + "-";

    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
      File tempDir = new File(baseDir, baseName + counter);
      if (tempDir.mkdir()) {
        return tempDir;
      }
    }
    throw new IllegalStateException(
        "Failed to create directory within "
            + TEMP_DIR_ATTEMPTS
            + " attempts (tried "
            + baseName
            + "0 to "
            + baseName
            + (TEMP_DIR_ATTEMPTS - 1)
            + ')');
  }

  /**
   * Creates an empty file or updates the last updated timestamp on the same as the unix command of
   * the same name.
   *
   * @param file the file to create or update
   * @throws IOException if an I/O error occurs
   */
  @Beta
  @SuppressWarnings("GoodTime") // reading system time without TimeSource
  public static void touch(File file) throws 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 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
   */
  @Beta
  public static void createParentDirs(File file) throws 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 a file from one path to another. This method can rename a file and/or move it to a
   * different directory. In either case {@code to} must be the target path for the file itself; not
   * just the new name for the file or the path to the new parent directory.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#move}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void move(File from, File to) throws IOException {
    checkNotNull(from);
    checkNotNull(to);
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);

    if (!from.renameTo(to)) {
      copy(from, to);
      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.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the first line, or null if the file is empty
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
   *     scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static String readFirstLine(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).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 {@code List}. For an {@code ImmutableList}, use {@code
   * Files.asCharSource(file, charset).readLines()}.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a mutable {@link List} containing all the lines
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static List<String> readLines(File file, Charset 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 asCharSource(file, charset)
        .readLines(
            new LineProcessor<List<String>>() {
              final List<String> result = Lists.newArrayList();

              @Override
              public boolean processLine(String line) {
                result.add(line);
                return true;
              }

              @Override
              public List<String> getResult() {
                return result;
              }
            });
  }

  /**
   * Streams lines from a {@link File}, stopping when our callback returns false, or we have read
   * all of the lines.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param callback the {@link LineProcessor} to use to handle the lines
   * @return the output of processing the lines
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
   *     scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
    return asCharSource(file, charset).readLines(callback);
  }

  /**
   * Process the bytes of a file.
   *
   *
(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
   *
   * @param file the file to read
   * @param processor the object to which the bytes of the file are passed.
   * @return the result of the byte processor
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
    return asByteSource(file).read(processor);
  }

  /**
   * Computes the hash code of the {@code file} using {@code hashFunction}.
   *
   * @param file the file to read
   * @param hashFunction the hash function to use to hash the data
   * @return the {@link HashCode} of all of the bytes in the file
   * @throws IOException if an I/O error occurs
   * @since 12.0
   * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
   *     be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static HashCode hash(File file, HashFunction hashFunction) throws IOException {
    return asByteSource(file).hash(hashFunction);
  }

  /**
   * Fully maps a file read-only in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @return a read-only buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file) throws IOException {
    checkNotNull(file);
    return map(file, MapMode.READ_ONLY);
  }

  /**
   * Fully maps a file in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
   * MapMode}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
    return mapInternal(file, mode, -1);
  }

  /**
   * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
   * long, long)} using the requested {@link MapMode}.
   *
   *
Files are mapped from offset 0 to {@code size}.
   *
   *
If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
   * with the requested {@code size}. Thus this method is useful for creating memory mapped files
   * which do not yet exist.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
    checkArgument(size >= 0, "size (%s) may not be negative", size);
    return mapInternal(file, mode, size);
  }

  private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
      throws IOException {
    checkNotNull(file);
    checkNotNull(mode);

    Closer closer = Closer.create();
    try {
      RandomAccessFile raf =
          closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
      FileChannel channel = closer.register(raf.getChannel());
      return channel.map(mode, 0, size == -1 ? channel.size() : 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 {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
   * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
   * sibling of {@code a} referred to by {@code b}.
   *
   * @since 11.0
   */
  @Beta
  public static String simplifyPath(String pathname) {
    checkNotNull(pathname);
    if (pathname.length() == 0) {
      return ".";
    }

    // split the path apart
    Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
    List<String> path = new ArrayList<>();

    // resolve ., .., and //
    for (String component : components) {
      switch (component) {
        case ".":
          continue;
        case "..":
          if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
            path.remove(path.size() - 1);
          } else {
            path.add("..");
          }
          break;
        default:
          path.add(component);
          break;
      }
    }

    // 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 '{@code .}'.
   *
   *
Note: This method simply returns everything after the last '{@code .}' in the file's
   * name as determined by {@link File#getName}. It does not account for any filesystem-specific
   * behavior that the {@link File} API does not already account for. For example, on NTFS it will
   * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
   * will drop the {@code ":.txt"} part of the name when the file is actually created on the
   * filesystem due to NTFS's Alternate Data Streams.
   *
   * @since 11.0
   */
  @Beta
  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 {@code basename} unix command. The result does not include the '{@code .}'.
   *
   * @param 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.
   * @return The file name without its path or extension.
   * @since 14.0
   */
  @Beta
  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 {@link TreeTraverser} instance for {@link File} trees.
   *
   *
Warning: {@code 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
   * @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
   *     {@link #fileTraverser()} instead with the same semantics as this method.
   */
  @Deprecated
  static TreeTraverser<File> fileTreeTraverser() {
    return FILE_TREE_TRAVERSER;
  }

  private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
      new TreeTraverser<File>() {
        @Override
        public Iterable<File> children(File file) {
          return fileTreeChildren(file);
        }

        @Override
        public String toString() {
          return "Files.fileTreeTraverser()";
        }
      };

  /**
   * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
   * starts from a {@link File} and will return all files and directories it encounters.
   *
   *
Warning: {@code 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.
   *
   *
If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
   * except that it doesn't follow symbolic links and returns {@code Path} instances.
   *
   *
If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
   * a directory, no exception will be thrown and the returned {@link Iterable} will contain a
   * single element: that file.
   *
   *
Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
   * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
   * "/home/alice", ...]}
   *
   * @since 23.5
   */
  @Beta
  public static Traverser<File> fileTraverser() {
    return Traverser.forTree(FILE_TREE);
  }

  private static final SuccessorsFunction<File> FILE_TREE =
      new SuccessorsFunction<File>() {
        @Override
        public Iterable<File> successors(File file) {
          return fileTreeChildren(file);
        }
      };

  private static Iterable<File> fileTreeChildren(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();
  }

  /**
   * Returns a predicate that returns the result of {@link File#isDirectory} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isDirectory() {
    return FilePredicate.IS_DIRECTORY;
  }

  /**
   * Returns a predicate that returns the result of {@link File#isFile} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isFile() {
    return FilePredicate.IS_FILE;
  }

  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()";
      }
    }
  }
}

## 内容2
### 文件路径：
guava/src/com/google/common/io/Files.java
### 代码内容：
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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Provides utility methods for working with {@linkplain File files}.
 *
 *
{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
 * JDK's {@link java.nio.file.Files} class.
 *
 * @author Chris Nokleberg
 * @author Colin Decker
 * @since 1.0
 */
@GwtIncompatible
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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered reader
   */
  @Beta
  public static BufferedReader newReader(File file, Charset 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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
   * java.nio.file.OpenOption...)}.
   *
   * @param file the file to write to
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered writer
   */
  @Beta
  public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
    checkNotNull(file);
    checkNotNull(charset);
    return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
  }

  /**
   * Returns a new {@link 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.file = checkNotNull(file);
    }

    @Override
    public FileInputStream openStream() throws IOException {
      return new FileInputStream(file);
    }

    @Override
    public Optional<Long> sizeIfKnown() {
      if (file.isFile()) {
        return Optional.of(file.length());
      } else {
        return Optional.absent();
      }
    }

    @Override
    public long size() throws IOException {
      if (!file.isFile()) {
        throw new FileNotFoundException(file.toString());
      }
      return file.length();
    }

    @Override
    public byte[] read() throws IOException {
      Closer closer = Closer.create();
      try {
        FileInputStream in = closer.register(openStream());
        return ByteStreams.toByteArray(in, in.getChannel().size());
      } catch (Throwable e) {
        throw closer.rethrow(e);
      } finally {
        closer.close();
      }
    }

    @Override
    public String toString() {
      return "Files.asByteSource(" + file + ")";
    }
  }

  /**
   * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
   * control how the file is opened for writing. When no mode is provided, the file will be
   * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
   * will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static ByteSink asByteSink(File file, FileWriteMode... modes) {
    return new FileByteSink(file, modes);
  }

  private static final class FileByteSink extends ByteSink {

    private final File file;
    private final ImmutableSet<FileWriteMode> modes;

    private FileByteSink(File file, FileWriteMode... modes) {
      this.file = checkNotNull(file);
      this.modes = ImmutableSet.copyOf(modes);
    }

    @Override
    public FileOutputStream openStream() throws IOException {
      return new FileOutputStream(file, modes.contains(APPEND));
    }

    @Override
    public String toString() {
      return "Files.asByteSink(" + file + ", " + modes + ")";
    }
  }

  /**
   * Returns a new {@link CharSource} for reading character data from the given file using the given
   * character set.
   *
   * @since 14.0
   */
  public static CharSource asCharSource(File file, Charset charset) {
    return asByteSource(file).asCharSource(charset);
  }

  /**
   * Returns a new {@link CharSink} for writing character data to the given file using the given
   * character set. The given {@code modes} control how the file is opened for writing. When no mode
   * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
   * APPEND} mode is provided, writes will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
    return asByteSink(file, modes).asCharSink(charset);
  }

  /**
   * Reads all bytes from a file into a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#readAllBytes}.
   *
   * @param file the file to read from
   * @return a byte array containing all the bytes from file
   * @throws IllegalArgumentException if the file is bigger than the largest possible byte array
   *     (2^31 - 1)
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static byte[] toByteArray(File file) throws IOException {
    return asByteSource(file).read();
  }

  /**
   * Reads all characters from a file into a {@link String}, using the given character set.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a string containing all the characters from the file
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  public static String toString(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).read();
  }

  /**
   * Overwrites a file with the contents of a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
   *
   * @param from the bytes to write
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void write(byte[] from, File to) throws IOException {
    asByteSink(to).write(from);
  }

  /**
   * Writes a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to write
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  public static void write(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset).write(from);
  }

  /**
   * Copies all bytes from a file to an output stream.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
   *
   * @param from the source file
   * @param to the output stream
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void copy(File from, OutputStream to) throws IOException {
    asByteSource(from).copyTo(to);
  }

  /**
   * Copies all the bytes from one file to another.
   *
   *
Copying is not an atomic operation - in the case of an I/O error, power loss, process
   * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
   * need to guard against those conditions, you should employ other file-level synchronization.
   *
   *
Warning: If {@code to} represents an existing file, that file will be overwritten
   * with the contents of {@code from}. If {@code to} and {@code from} refer to the same
   * file, the contents of that file will be deleted.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

  /**
   * Copies all characters from a file to an appendable object, using the given character set.
   *
   * @param from the source file
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param to the appendable object
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
   *     be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static void copy(File from, Charset charset, Appendable to) throws IOException {
    asCharSource(from, charset).copyTo(to);
  }

  /**
   * Appends a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to append
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
   *     method is scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static void append(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset, FileWriteMode.APPEND).write(from);
  }

  /**
   * Returns true if the given files exist, are not directories, and contain the same bytes.
   *
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static boolean equal(File file1, File file2) throws 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 {@code java.io.tmpdir} system property), and returns its name.
   *
   *
Use this method instead of {@link File#createTempFile(String, String)} when you wish to
   * create a directory, not a regular file. A common pitfall is to call {@code 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.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#createTempDirectory}.
   *
   * @return the newly-created directory
   * @throws IllegalStateException if the directory could not be created
   */
  @Beta
  public static File createTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    @SuppressWarnings("GoodTime") // reading system time without TimeSource
    String baseName = System.currentTimeMillis() + "-";

    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
      File tempDir = new File(baseDir, baseName + counter);
      if (tempDir.mkdir()) {
        return tempDir;
      }
    }
    throw new IllegalStateException(
        "Failed to create directory within "
            + TEMP_DIR_ATTEMPTS
            + " attempts (tried "
            + baseName
            + "0 to "
            + baseName
            + (TEMP_DIR_ATTEMPTS - 1)
            + ')');
  }

  /**
   * Creates an empty file or updates the last updated timestamp on the same as the unix command of
   * the same name.
   *
   * @param file the file to create or update
   * @throws IOException if an I/O error occurs
   */
  @Beta
  @SuppressWarnings("GoodTime") // reading system time without TimeSource
  public static void touch(File file) throws 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 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
   */
  @Beta
  public static void createParentDirs(File file) throws 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 a file from one path to another. This method can rename a file and/or move it to a
   * different directory. In either case {@code to} must be the target path for the file itself; not
   * just the new name for the file or the path to the new parent directory.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#move}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void move(File from, File to) throws IOException {
    checkNotNull(from);
    checkNotNull(to);
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);

    if (!from.renameTo(to)) {
      copy(from, to);
      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.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the first line, or null if the file is empty
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
   *     scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static String readFirstLine(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).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 {@code List}. For an {@code ImmutableList}, use {@code
   * Files.asCharSource(file, charset).readLines()}.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a mutable {@link List} containing all the lines
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static List<String> readLines(File file, Charset 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 asCharSource(file, charset)
        .readLines(
            new LineProcessor<List<String>>() {
              final List<String> result = Lists.newArrayList();

              @Override
              public boolean processLine(String line) {
                result.add(line);
                return true;
              }

              @Override
              public List<String> getResult() {
                return result;
              }
            });
  }

  /**
   * Streams lines from a {@link File}, stopping when our callback returns false, or we have read
   * all of the lines.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param callback the {@link LineProcessor} to use to handle the lines
   * @return the output of processing the lines
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
   *     scheduled to be removed in October 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
    return asCharSource(file, charset).readLines(callback);
  }

  /**
   * Process the bytes of a file.
   *
   *
(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
   *
   * @param file the file to read
   * @param processor the object to which the bytes of the file are passed.
   * @return the result of the byte processor
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
   *     removed in October 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
    return asByteSource(file).read(processor);
  }

  /**
   * Computes the hash code of the {@code file} using {@code hashFunction}.
   *
   * @param file the file to read
   * @param hashFunction the hash function to use to hash the data
   * @return the {@link HashCode} of all of the bytes in the file
   * @throws IOException if an I/O error occurs
   * @since 12.0
   * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
   *     be removed in October 2019.
   */
  @Beta
  @Deprecated
  public
  static HashCode hash(File file, HashFunction hashFunction) throws IOException {
    return asByteSource(file).hash(hashFunction);
  }

  /**
   * Fully maps a file read-only in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @return a read-only buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file) throws IOException {
    checkNotNull(file);
    return map(file, MapMode.READ_ONLY);
  }

  /**
   * Fully maps a file in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
   * MapMode}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
    return mapInternal(file, mode, -1);
  }

  /**
   * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
   * long, long)} using the requested {@link MapMode}.
   *
   *
Files are mapped from offset 0 to {@code size}.
   *
   *
If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
   * with the requested {@code size}. Thus this method is useful for creating memory mapped files
   * which do not yet exist.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
    checkArgument(size >= 0, "size (%s) may not be negative", size);
    return mapInternal(file, mode, size);
  }

  private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
      throws IOException {
    checkNotNull(file);
    checkNotNull(mode);

    Closer closer = Closer.create();
    try {
      RandomAccessFile raf =
          closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
      FileChannel channel = closer.register(raf.getChannel());
      return channel.map(mode, 0, size == -1 ? channel.size() : 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 {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
   * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
   * sibling of {@code a} referred to by {@code b}.
   *
   * @since 11.0
   */
  @Beta
  public static String simplifyPath(String pathname) {
    checkNotNull(pathname);
    if (pathname.length() == 0) {
      return ".";
    }

    // split the path apart
    Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
    List<String> path = new ArrayList<>();

    // resolve ., .., and //
    for (String component : components) {
      switch (component) {
        case ".":
          continue;
        case "..":
          if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
            path.remove(path.size() - 1);
          } else {
            path.add("..");
          }
          break;
        default:
          path.add(component);
          break;
      }
    }

    // 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 '{@code .}'.
   *
   *
Note: This method simply returns everything after the last '{@code .}' in the file's
   * name as determined by {@link File#getName}. It does not account for any filesystem-specific
   * behavior that the {@link File} API does not already account for. For example, on NTFS it will
   * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
   * will drop the {@code ":.txt"} part of the name when the file is actually created on the
   * filesystem due to NTFS's Alternate Data Streams.
   *
   * @since 11.0
   */
  @Beta
  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 {@code basename} unix command. The result does not include the '{@code .}'.
   *
   * @param 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.
   * @return The file name without its path or extension.
   * @since 14.0
   */
  @Beta
  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 {@link TreeTraverser} instance for {@link File} trees.
   *
   *
Warning: {@code 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
   * @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
   *     {@link #fileTraverser()} instead with the same semantics as this method.
   */
  @Deprecated
  static TreeTraverser<File> fileTreeTraverser() {
    return FILE_TREE_TRAVERSER;
  }

  private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
      new TreeTraverser<File>() {
        @Override
        public Iterable<File> children(File file) {
          return fileTreeChildren(file);
        }

        @Override
        public String toString() {
          return "Files.fileTreeTraverser()";
        }
      };

  /**
   * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
   * starts from a {@link File} and will return all files and directories it encounters.
   *
   *
Warning: {@code 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.
   *
   *
If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
   * except that it doesn't follow symbolic links and returns {@code Path} instances.
   *
   *
If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
   * a directory, no exception will be thrown and the returned {@link Iterable} will contain a
   * single element: that file.
   *
   *
Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
   * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
   * "/home/alice", ...]}
   *
   * @since 23.5
   */
  @Beta
  public static Traverser<File> fileTraverser() {
    return Traverser.forTree(FILE_TREE);
  }

  private static final SuccessorsFunction<File> FILE_TREE =
      new SuccessorsFunction<File>() {
        @Override
        public Iterable<File> successors(File file) {
          return fileTreeChildren(file);
        }
      };

  private static Iterable<File> fileTreeChildren(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();
  }

  /**
   * Returns a predicate that returns the result of {@link File#isDirectory} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isDirectory() {
    return FilePredicate.IS_DIRECTORY;
  }

  /**
   * Returns a predicate that returns the result of {@link File#isFile} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isFile() {
    return FilePredicate.IS_FILE;
  }

  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()";
      }
    }
  }
}

Output:
【漏洞类型】临时文件创建漏洞
【严重性】中等
【漏洞摘要】`Files.createTempDir()`方法在创建临时目录时使用了系统默认的临时目录（由`java.io.tmpdir`系统属性定义），这可能导致临时文件的可见性增加，被恶意程序读取或覆盖。此外，该方法假设临时卷是可写的，并且有足够的空闲inode和块，但没有提供任何机制来确保这些条件在实际运行环境中得到满足。
【关键代码模式】`createTempDir()`方法，`System.getProperty("java.io.tmpdir")`，`mkdir()`方法。
【修复方法说明】此修复方法通过在Javadoc中添加警告信息，指出在特定环境中使用该方法存在的风险，并建议使用更安全的替代方法。


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
modules/kernel/src/main/java/org/opencastproject/kernel/http/impl/HttpClientImpl.java
### 代码内容：
/**
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 *
 * The Apereo Foundation licenses this file to you under the Educational
 * Community 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://opensource.org/licenses/ecl2.txt
 *
 * 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 org.opencastproject.kernel.http.impl;

import org.opencastproject.kernel.http.api.HttpClient;

import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/** Implementation of HttpClient that makes http requests. */
public class HttpClientImpl implements HttpClient {

  /** The logging facility */
  private static final Logger logger = LoggerFactory.getLogger(HttpClientImpl.class);

  /** client used for all http requests. */
  private DefaultHttpClient defaultHttpClient = makeHttpClient();

  /** See org.opencastproject.kernel.http.api.HttpClient */
  @Override
  public HttpParams getParams() {
    return defaultHttpClient.getParams();
  }

  /** See org.opencastproject.kernel.http.api.HttpClient */
  @Override
  public CredentialsProvider getCredentialsProvider() {
    return defaultHttpClient.getCredentialsProvider();
  }

  /** See org.opencastproject.kernel.http.api.HttpClient */
  @Override
  public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException {
    return defaultHttpClient.execute(httpUriRequest);
  }

  /** See org.opencastproject.kernel.http.api.HttpClient */
  @Override
  public ClientConnectionManager getConnectionManager() {
    return defaultHttpClient.getConnectionManager();
  }

  /**
   * Creates a new client that can deal with all kinds of oddities with regards to http/https connections.
   *
   * @return the client
   */
  private DefaultHttpClient makeHttpClient() {

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    try {
      logger.debug("Installing forgiving hostname verifier and trust managers");
      X509TrustManager trustManager = createTrustManager();
      X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
      SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
      ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
      SchemeRegistry sr = ccm.getSchemeRegistry();
      sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
      logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    } catch (KeyManagementException e) {
      logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    }

    return defaultHttpClient;
  }

  /**
   * Returns a new trust manager which will be in charge of checking the SSL certificates that are being presented by
   * SSL enabled hosts.
   *
   * @return the trust manager
   */
  private X509TrustManager createTrustManager() {
    X509TrustManager trustManager = new X509TrustManager() {

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
       */
      public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        logger.trace("Skipping trust check on client certificate {}", string);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
       */
      public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        logger.trace("Skipping trust check on server certificate {}", string);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
       */
      public X509Certificate[] getAcceptedIssuers() {
        logger.trace("Returning empty list of accepted issuers");
        return null;
      }

    };

    return trustManager;
  }

  /**
   * Creates a host name verifier that will make sure the SSL host's name matches the name in the SSL certificate.
   *
   * @return the host name verifier
   */
  private X509HostnameVerifier createHostNameVerifier() {
    X509HostnameVerifier verifier = new X509HostnameVerifier() {

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket)
       */
      public void verify(String host, SSLSocket ssl) throws IOException {
        logger.trace("Skipping SSL host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate)
       */
      public void verify(String host, X509Certificate xc) throws SSLException {
        logger.trace("Skipping X509 certificate host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[],
       *      java.lang.String[])
       */
      public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        logger.trace("Skipping DNS host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession)
       */
      public boolean verify(String host, SSLSession ssl) {
        logger.trace("Skipping SSL session host name check on {}", host);
        return true;
      }
    };

    return verifier;
  }

}

Output:
【漏洞类型】信任管理器和主机名验证器的漏洞
【严重性】High
【漏洞摘要】原始代码中的`HttpClientImpl`类在处理HTTPS连接时，通过自定义的信任管理器和主机名验证器，跳过了对客户端和服务器证书的信任检查，以及对主机名的验证。这种做法会使得HTTPS连接变得不安全，容易受到中间人攻击（Man-in-the-Middle, MITM）。
【关键代码模式】
- `createTrustManager()`方法：自定义了一个`X509TrustManager`，跳过了对客户端和服务器证书的信任检查，并返回了一个空的受信任颁发者列表。
- `createHostNameVerifier()`方法：自定义了一个`X509HostnameVerifier`，跳过了对SSL主机名和X509证书主机名的验证，并返回了`true`。
【修复方法说明】修复方法通过移除自定义的信任管理器和主机名验证器，恢复了默认的HTTPS安全验证。这样可以确保在处理HTTPS连接时，对证书的有效性和主机名进行严格的验证，从而增强系统的安全性。


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java
### 代码内容：
package org.springframework.cloud.task.repository.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.sql.DataSource;

import org.springframework.batch.item.database.Order;
import org.springframework.cloud.task.configuration.TaskProperties;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.database.PagingQueryProvider;
import org.springframework.cloud.task.repository.database.support.SqlPagingQueryProviderFactoryBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * Stores Task Execution Information to a JDBC DataSource.
 *
 * @author Glenn Renfro
 * @author Gunnar Hillert
 * @author David Turanski
 * @author Ilayaperumal Gopinathan
 */
public class JdbcTaskExecutionDao implements TaskExecutionDao {

	/**
	 * SELECT clause for task execution.
	 */
	public static final String SELECT_CLAUSE = "TASK_EXECUTION_ID, "
			+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
			+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, "
			+ "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID ";

	/**
	 * FROM clause for task execution.
	 */
	public static final String FROM_CLAUSE = "%PREFIX%EXECUTION";

	/**
	 * WHERE clause for running task.
	 */
	public static final String RUNNING_TASK_WHERE_CLAUSE = "where TASK_NAME = :taskName AND END_TIME IS NULL ";

	/**
	 * WHERE clause for task name.
	 */
	public static final String TASK_NAME_WHERE_CLAUSE = "where TASK_NAME = :taskName ";

	private static final String SAVE_TASK_EXECUTION = "INSERT into %PREFIX%EXECUTION"
			+ "(TASK_EXECUTION_ID, EXIT_CODE, START_TIME, TASK_NAME, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID)"
			+ "values (:taskExecutionId, :exitCode, :startTime, "
			+ ":taskName, :lastUpdated, :externalExecutionId, :parentExecutionId)";

	private static final String CREATE_TASK_ARGUMENT = "INSERT into "
			+ "%PREFIX%EXECUTION_PARAMS(TASK_EXECUTION_ID, TASK_PARAM ) values (:taskExecutionId, :taskParam)";

	private static final String START_TASK_EXECUTION_PREFIX = "UPDATE %PREFIX%EXECUTION set "
			+ "START_TIME = :startTime, TASK_NAME = :taskName, LAST_UPDATED = :lastUpdated";

	private static final String START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX = ", "
			+ "EXTERNAL_EXECUTION_ID = :externalExecutionId, PARENT_EXECUTION_ID = :parentExecutionId "
			+ "where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String START_TASK_EXECUTION_SUFFIX = ", PARENT_EXECUTION_ID = :parentExecutionId "
			+ "where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String CHECK_TASK_EXECUTION_EXISTS = "SELECT COUNT(*) FROM "
			+ "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = :taskExecutionId";

	private static final String UPDATE_TASK_EXECUTION = "UPDATE %PREFIX%EXECUTION set "
			+ "END_TIME = :endTime, EXIT_CODE = :exitCode, EXIT_MESSAGE = :exitMessage, ERROR_MESSAGE = :errorMessage, "
			+ "LAST_UPDATED = :lastUpdated where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID = "UPDATE %PREFIX%EXECUTION set "
			+ "EXTERNAL_EXECUTION_ID = :externalExecutionId where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String GET_EXECUTION_BY_ID = "SELECT TASK_EXECUTION_ID, "
			+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
			+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, "
			+ "PARENT_EXECUTION_ID "
			+ "from %PREFIX%EXECUTION where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String FIND_ARGUMENT_FROM_ID = "SELECT TASK_EXECUTION_ID, "
			+ "TASK_PARAM from %PREFIX%EXECUTION_PARAMS where TASK_EXECUTION_ID = :taskExecutionId";

	private static final String TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM "
			+ "%PREFIX%EXECUTION ";

	private static final String TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM "
			+ "%PREFIX%EXECUTION where TASK_NAME = :taskName";

	private static final String RUNNING_TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM "
			+ "%PREFIX%EXECUTION where TASK_NAME = :taskName AND END_TIME IS NULL ";

	private static final String RUNNING_TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM "
			+ "%PREFIX%EXECUTION where END_TIME IS NULL ";

	private static final String LAST_TASK_EXECUTIONS_BY_TASK_NAMES = "select TE2.* from ("
			+ "select MAX(TE.TASK_EXECUTION_ID) as TASK_EXECUTION_ID, TE.TASK_NAME, TE.START_TIME from ("
			+ "select TASK_NAME, MAX(START_TIME) as START_TIME"
			+ "      FROM %PREFIX%EXECUTION where TASK_NAME in (:taskNames)"
			+ "      GROUP BY TASK_NAME" + ") TE_MAX "
			+ "inner join %PREFIX%EXECUTION TE ON TE.TASK_NAME = TE_MAX.TASK_NAME AND TE.START_TIME = TE_MAX.START_TIME "
			+ "group by TE.TASK_NAME, TE.START_TIME" + ") TE1 "
			+ "inner join %PREFIX%EXECUTION TE2 ON TE1.TASK_EXECUTION_ID = TE2.TASK_EXECUTION_ID "
			+ "order by TE2.START_TIME DESC, TE2.TASK_EXECUTION_ID DESC";

	private static final String FIND_TASK_NAMES = "SELECT distinct TASK_NAME from %PREFIX%EXECUTION order by TASK_NAME";

	private static final String FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID = "SELECT TASK_EXECUTION_ID FROM "
			+ "%PREFIX%TASK_BATCH WHERE JOB_EXECUTION_ID = :jobExecutionId";

	private static final String FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID = "SELECT JOB_EXECUTION_ID "
			+ "FROM %PREFIX%TASK_BATCH WHERE TASK_EXECUTION_ID = :taskExecutionId";

	private final NamedParameterJdbcTemplate jdbcTemplate;

	private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX;

	private DataSource dataSource;

	private LinkedHashMap<String, Order> orderMap;

	private DataFieldMaxValueIncrementer taskIncrementer;

	/**
	 * Initializes the JdbcTaskExecutionDao.
	 * @param dataSource used by the dao to execute queries and update the tables.
	 * @param tablePrefix the table prefix to use for this dao.
	 */
	public JdbcTaskExecutionDao(DataSource dataSource, String tablePrefix) {
		this(dataSource);
		Assert.hasText(tablePrefix, "tablePrefix must not be null nor empty");
		this.tablePrefix = tablePrefix;
	}

	/**
	 * Initializes the JdbTaskExecutionDao and defaults the table prefix to
	 * {@link TaskProperties#DEFAULT_TABLE_PREFIX}.
	 * @param dataSource used by the dao to execute queries and update the tables.
	 */
	public JdbcTaskExecutionDao(DataSource dataSource) {
		Assert.notNull(dataSource, "The dataSource must not be null.");
		this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
		this.dataSource = dataSource;
		this.orderMap = new LinkedHashMap<>();
		this.orderMap.put("START_TIME", Order.DESCENDING);
		this.orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING);
	}

	@Override
	public TaskExecution createTaskExecution(String taskName, Date startTime,
			List<String> arguments, String externalExecutionId) {
		return createTaskExecution(taskName, startTime, arguments, externalExecutionId,
				null);
	}

	@Override
	public TaskExecution createTaskExecution(String taskName, Date startTime,
			List<String> arguments, String externalExecutionId, Long parentExecutionId) {
		long nextExecutionId = getNextExecutionId();

		TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName,
				startTime, null, null, arguments, null, externalExecutionId);

		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskExecutionId", nextExecutionId, Types.BIGINT)
				.addValue("exitCode", null, Types.INTEGER)
				.addValue("startTime", startTime, Types.TIMESTAMP)
				.addValue("taskName", taskName, Types.VARCHAR)
				.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
				.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR)
				.addValue("parentExecutionId", parentExecutionId, Types.BIGINT);

		this.jdbcTemplate.update(getQuery(SAVE_TASK_EXECUTION), queryParameters);
		insertTaskArguments(nextExecutionId, arguments);
		return taskExecution;
	}

	@Override
	public TaskExecution startTaskExecution(long executionId, String taskName,
			Date startTime, List<String> arguments, String externalExecutionId) {
		return startTaskExecution(executionId, taskName, startTime, arguments,
				externalExecutionId, null);
	}

	@Override
	public TaskExecution startTaskExecution(long executionId, String taskName,
			Date startTime, List<String> arguments, String externalExecutionId,
			Long parentExecutionId) {
		TaskExecution taskExecution = new TaskExecution(executionId, null, taskName,
				startTime, null, null, arguments, null, externalExecutionId,
				parentExecutionId);

		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("startTime", startTime, Types.TIMESTAMP)
				.addValue("exitCode", null, Types.INTEGER)
				.addValue("taskName", taskName, Types.VARCHAR)
				.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
				.addValue("parentExecutionId", parentExecutionId, Types.BIGINT)
				.addValue("taskExecutionId", executionId, Types.BIGINT);

		String updateString = START_TASK_EXECUTION_PREFIX;

		if (externalExecutionId == null) {
			updateString += START_TASK_EXECUTION_SUFFIX;
		}
		else {
			updateString += START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX;
			queryParameters.addValue("externalExecutionId", externalExecutionId,
					Types.VARCHAR);
		}

		this.jdbcTemplate.update(getQuery(updateString), queryParameters);
		insertTaskArguments(executionId, arguments);
		return taskExecution;
	}

	@Override
	public void completeTaskExecution(long taskExecutionId, Integer exitCode,
			Date endTime, String exitMessage, String errorMessage) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);

		// Check if given TaskExecution's Id already exists, if none is found
		// it is invalid and an exception should be thrown.
		if (this.jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS),
				queryParameters, Integer.class) != 1) {
			throw new IllegalStateException(
					"Invalid TaskExecution, ID " + taskExecutionId + " not found.");
		}

		final MapSqlParameterSource parameters = new MapSqlParameterSource()
				.addValue("endTime", endTime, Types.TIMESTAMP)
				.addValue("exitCode", exitCode, Types.INTEGER)
				.addValue("exitMessage", exitMessage, Types.VARCHAR)
				.addValue("errorMessage", errorMessage, Types.VARCHAR)
				.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
				.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);

		this.jdbcTemplate.update(getQuery(UPDATE_TASK_EXECUTION), parameters);
	}

	@Override
	public void completeTaskExecution(long taskExecutionId, Integer exitCode,
			Date endTime, String exitMessage) {
		completeTaskExecution(taskExecutionId, exitCode, endTime, exitMessage, null);
	}

	@Override
	public TaskExecution getTaskExecution(long executionId) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskExecutionId", executionId, Types.BIGINT);

		try {
			TaskExecution taskExecution = this.jdbcTemplate.queryForObject(
					getQuery(GET_EXECUTION_BY_ID), queryParameters,
					new TaskExecutionRowMapper());
			taskExecution.setArguments(getTaskArguments(executionId));
			return taskExecution;
		}
		catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public long getTaskExecutionCountByTaskName(String taskName) {

		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskName", taskName, Types.VARCHAR);

		try {
			return this.jdbcTemplate.queryForObject(
					getQuery(TASK_EXECUTION_COUNT_BY_NAME), queryParameters, Long.class);
		}
		catch (EmptyResultDataAccessException e) {
			return 0;
		}
	}

	@Override
	public long getRunningTaskExecutionCountByTaskName(String taskName) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskName", taskName, Types.VARCHAR);

		try {
			return this.jdbcTemplate.queryForObject(
					getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters,
					Long.class);
		}
		catch (EmptyResultDataAccessException e) {
			return 0;
		}
	}

	@Override
	public long getRunningTaskExecutionCount() {

		try {
			final MapSqlParameterSource queryParameters = new MapSqlParameterSource();
			return this.jdbcTemplate.queryForObject(
					getQuery(RUNNING_TASK_EXECUTION_COUNT), queryParameters, Long.class);
		}
		catch (EmptyResultDataAccessException e) {
			return 0;
		}
	}

	@Override
	public List<TaskExecution> getLatestTaskExecutionsByTaskNames(String... taskNames) {
		Assert.notEmpty(taskNames, "At least 1 task name must be provided.");

		final List<String> taskNamesAsList = new ArrayList<>();

		for (String taskName : taskNames) {
			if (StringUtils.hasText(taskName)) {
				taskNamesAsList.add(taskName);
			}
		}

		Assert.isTrue(taskNamesAsList.size() == taskNames.length, String.format(
				"Task names must not contain any empty elements but %s of %s were empty or null.",
				taskNames.length - taskNamesAsList.size(), taskNames.length));

		try {
			final Map<String, List<String>> paramMap = Collections
					.singletonMap("taskNames", taskNamesAsList);
			return this.jdbcTemplate.query(getQuery(LAST_TASK_EXECUTIONS_BY_TASK_NAMES),
					paramMap, new TaskExecutionRowMapper());
		}
		catch (EmptyResultDataAccessException e) {
			return Collections.emptyList();
		}
	}

	@Override
	public TaskExecution getLatestTaskExecutionForTaskName(String taskName) {
		Assert.hasText(taskName, "The task name must not be empty.");
		final List<TaskExecution> taskExecutions = this
				.getLatestTaskExecutionsByTaskNames(taskName);
		if (taskExecutions.isEmpty()) {
			return null;
		}
		else if (taskExecutions.size() == 1) {
			return taskExecutions.get(0);
		}
		else {
			throw new IllegalStateException(
					"Only expected a single TaskExecution but received "
							+ taskExecutions.size());
		}
	}

	@Override
	public long getTaskExecutionCount() {

		try {
			return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT),
					new MapSqlParameterSource(), Long.class);
		}
		catch (EmptyResultDataAccessException e) {
			return 0;
		}
	}

	@Override
	public Page<TaskExecution> findRunningTaskExecutions(String taskName,
			Pageable pageable) {
		return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE,
				RUNNING_TASK_WHERE_CLAUSE,
				new MapSqlParameterSource("taskName", taskName),
				getRunningTaskExecutionCountByTaskName(taskName));
	}

	@Override
	public Page<TaskExecution> findTaskExecutionsByName(String taskName,
			Pageable pageable) {
		return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE,
				TASK_NAME_WHERE_CLAUSE, new MapSqlParameterSource("taskName", taskName),
				getTaskExecutionCountByTaskName(taskName));
	}

	@Override
	public List<String> getTaskNames() {
		return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES),
				new MapSqlParameterSource(), String.class);
	}

	@Override
	public Page<TaskExecution> findAll(Pageable pageable) {
		return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, null,
				new MapSqlParameterSource(), getTaskExecutionCount());
	}

	public void setTaskIncrementer(DataFieldMaxValueIncrementer taskIncrementer) {
		this.taskIncrementer = taskIncrementer;
	}

	public long getNextExecutionId() {
		return this.taskIncrementer.nextLongValue();
	}

	@Override
	public Long getTaskExecutionIdByJobExecutionId(long jobExecutionId) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("jobExecutionId", jobExecutionId, Types.BIGINT);

		try {
			return this.jdbcTemplate.queryForObject(
					getQuery(FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID), queryParameters,
					Long.class);
		}
		catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public Set<Long> getJobExecutionIdsByTaskExecutionId(long taskExecutionId) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);

		try {
			return this.jdbcTemplate.query(
					getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID), queryParameters,
					new ResultSetExtractor<Set<Long>>() {
						@Override
						public Set<Long> extractData(ResultSet resultSet)
								throws SQLException, DataAccessException {
							Set<Long> jobExecutionIds = new TreeSet<>();

							while (resultSet.next()) {
								jobExecutionIds
										.add(resultSet.getLong("JOB_EXECUTION_ID"));
							}

							return jobExecutionIds;
						}
					});
		}
		catch (DataAccessException e) {
			return Collections.emptySet();
		}
	}

	@Override
	public void updateExternalExecutionId(long taskExecutionId,
			String externalExecutionId) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR)
				.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);

		if (this.jdbcTemplate.update(
				getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID),
				queryParameters) != 1) {
			throw new IllegalStateException(
					"Invalid TaskExecution, ID " + taskExecutionId + " not found.");
		}
	}

	private Page<TaskExecution> queryForPageableResults(Pageable pageable,
			String selectClause, String fromClause, String whereClause,
			MapSqlParameterSource queryParameters, long totalCount) {
		SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean();
		factoryBean.setSelectClause(selectClause);
		factoryBean.setFromClause(fromClause);
		if (StringUtils.hasText(whereClause)) {
			factoryBean.setWhereClause(whereClause);
		}
		final Sort sort = pageable.getSort();
		final LinkedHashMap<String, Order> sortOrderMap = new LinkedHashMap<>();

		if (sort != null) {
			for (Sort.Order sortOrder : sort) {
				sortOrderMap.put(sortOrder.getProperty(),
						sortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);
			}
		}

		if (!CollectionUtils.isEmpty(sortOrderMap)) {
			factoryBean.setSortKeys(sortOrderMap);
		}
		else {
			factoryBean.setSortKeys(this.orderMap);
		}

		factoryBean.setDataSource(this.dataSource);
		PagingQueryProvider pagingQueryProvider;
		try {
			pagingQueryProvider = factoryBean.getObject();
			pagingQueryProvider.init(this.dataSource);
		}
		catch (Exception e) {
			throw new IllegalStateException(e);
		}
		String query = pagingQueryProvider.getPageQuery(pageable);
		List<TaskExecution> resultList = this.jdbcTemplate.query(getQuery(query),
				queryParameters, new TaskExecutionRowMapper());
		return new PageImpl<>(resultList, pageable, totalCount);
	}

	private String getQuery(String base) {
		return StringUtils.replace(base, "%PREFIX%", this.tablePrefix);
	}

	/**
	 * Convenience method that inserts all arguments from the provided task arguments.
	 * @param executionId The executionId to which the arguments are associated.
	 * @param taskArguments The arguments to be stored.
	 */
	private void insertTaskArguments(long executionId, List<String> taskArguments) {
		for (String args : taskArguments) {
			insertArgument(executionId, args);
		}
	}

	/**
	 * Convenience method that inserts an individual records into the
	 * TASK_EXECUTION_PARAMS table.
	 * @param taskExecutionId id of a task execution
	 * @param taskParam task parameters
	 */
	private void insertArgument(long taskExecutionId, String taskParam) {
		final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
				.addValue("taskExecutionId", taskExecutionId, Types.BIGINT)
				.addValue("taskParam", taskParam, Types.VARCHAR);
		this.jdbcTemplate.update(getQuery(CREATE_TASK_ARGUMENT), queryParameters);
	}

	private List<String> getTaskArguments(long taskExecutionId) {
		final List<String> params = new ArrayList<>();
		RowCallbackHandler handler = new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				params.add(rs.getString(2));
			}
		};
		this.jdbcTemplate.query(getQuery(FIND_ARGUMENT_FROM_ID),
				new MapSqlParameterSource("taskExecutionId", taskExecutionId), handler);
		return params;
	}

	/**
	 * Re-usable mapper for {@link TaskExecution} instances.
	 *
	 */
	private final class TaskExecutionRowMapper implements RowMapper<TaskExecution> {

		private TaskExecutionRowMapper() {
		}

		@Override
		public TaskExecution mapRow(ResultSet rs, int rowNum) throws SQLException {
			long id = rs.getLong("TASK_EXECUTION_ID");
			Long parentExecutionId = rs.getLong("PARENT_EXECUTION_ID");
			if (rs.wasNull()) {
				parentExecutionId = null;
			}
			return new TaskExecution(id, getNullableExitCode(rs),
					rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"),
					rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"),
					getTaskArguments(id), rs.getString("ERROR_MESSAGE"),
					rs.getString("EXTERNAL_EXECUTION_ID"), parentExecutionId);
		}

		private Integer getNullableExitCode(ResultSet rs) throws SQLException {
			int exitCode = rs.getInt("EXIT_CODE");
			return !rs.wasNull() ? exitCode : null;
		}

	}

}

Output:
【漏洞类型】SQL注入漏洞
【严重性】High
【漏洞摘要】此代码存在SQL注入漏洞，因为`pageable.getSort()`返回的排序键没有被验证是否为有效列名。攻击者可以利用这一点通过构造特定的排序值来执行任意SQL代码，从而潜在地访问、修改或删除数据库中的数据。
【关键代码模式】
- `private Page<TaskExecution> queryForPageableResults(Pageable pageable, ...)`函数中的排序处理部分。
- `sortOrderMap.put(sortOrder.getProperty(), ...)`这一行代码，直接将用户提供的排序键插入到SQL查询中。
- `String query = pagingQueryProvider.getPageQuery(pageable);`这一行代码，生成最终的SQL查询。
【修复方法说明】
- 修复方法通过引入一个静态的`HashSet`来存储有效的排序列名，并在处理排序键时检查其有效性。
- 如果排序键不在有效列名集合中，抛出`IllegalArgumentException`异常。
- 最佳实践是始终对用户输入进行验证，以防止SQL注入等攻击。