FileUtils

package org.apache.solr.util;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * 文件复制,回写硬盘等操作
 */
public class FileUtils {

  /**
   * Resolves a path relative a base directory.
   *
   * <p>
   * This method does what "new File(base,path)" <b>Should</b> do, if it wasn't
   * completely lame: If path is absolute, then a File for that path is returned;
   * if it's not absolute, then a File is returned using "path" as a child
   * of "base")
   * </p>
   */
  public static File resolvePath(File base, String path) {
    File r = new File(path);
    return r.isAbsolute() ? r : new File(base, path);
  }

  public static void copyFile(File src , File destination) throws IOException {
    FileChannel in = null;
    FileChannel out = null;
    try {
      in = new FileInputStream(src).getChannel();
      out = new FileOutputStream(destination).getChannel();
      in.transferTo(0, in.size(), out);
    } finally {
      try { if (in != null) in.close(); } catch (IOException e) {}
      try { if (out != null) out.close(); } catch (IOException e) {}
    }
  }

  /**
   * Copied from Lucene's FSDirectory.fsync(String)
   *
   * @param fullFile the File to be synced to disk
   * @throws IOException if the file could not be synced
   */
  public static void sync(File fullFile) throws IOException  {
    if (fullFile == null || !fullFile.exists())
      throw new FileNotFoundException("File does not exist " + fullFile);

    boolean success = false;
    int retryCount = 0;
    IOException exc = null;
    while(!success && retryCount < 5) {
      retryCount++;
      RandomAccessFile file = null;
      try {
        try {
          file = new RandomAccessFile(fullFile, "rw");
          file.getFD().sync();
          success = true;
        } finally {
          if (file != null)
            file.close();
        }
      } catch (IOException ioe) {
        if (exc == null)
          exc = ioe;
        try {
          // Pause 5 msec
          Thread.sleep(5);
        } catch (InterruptedException ie) {
          Thread.currentThread().interrupt();
        }
      }
    }
    if (!success)
      // Throw original exception
      throw exc;
  }

  public static boolean fileExists(String filePathString) {
    return new File(filePathString).exists();
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值