Directory抽象类及其子类的总结 (4)

// 获取文件name最后修改的时间
public long fileModified(String name) {
    File file = new File(directory, name);
    return file.lastModified();
}

// 返回目录文件directory下名称为name的文件最后修改的时间
public static long fileModified(File directory, String name) {
    File file = new File(directory, name);
    return file.lastModified();
}

// 设置文件name当前修改的时间
public void touchFile(String name) {
    File file = new File(directory, name);
    file.setLastModified(System.currentTimeMillis());
}

// 获取文件name的长度
public long fileLength(String name) {
    File file = new File(directory, name);
    return file.length();
}

// 删除目录文件directory下的name文件
public void deleteFile(String name) throws IOException {
    File file = new File(directory, name);
    if (!file.delete())
      throw new IOException("Cannot delete " + file);
}

// 重新命名文件,该方法已经废弃
public synchronized void renameFile(String from, String to)
      throws IOException {
    File old = new File(directory, from);
    File nu = new File(directory, to);

if (nu.exists())
      if (!nu.delete())
        throw new IOException("Cannot delete " + nu);
    if (!old.renameTo(nu)) {
      java.io.InputStream in = null;
      java.io.OutputStream out = null;
      try {
        in = new FileInputStream(old);
        out = new FileOutputStream(nu);
        if (buffer == null) {
          buffer = new byte[1024];
        }
        int len;
        while ((len = in.read(buffer)) >= 0) {
          out.write(buffer, 0, len);
        }

old.delete();
      }
      catch (IOException ioe) {
        IOException newExc = new IOException("Cannot rename " + old + " to " + nu);
        newExc.initCause(ioe);
        throw newExc;
      }
      finally {
        try {
          if (in != null) {
            try {
              in.close();
            } catch (IOException e) {
              throw new RuntimeException("Cannot close input stream: " + e.toString(), e);
            }
          }
        } finally {
          if (out != null) {
            try {
              out.close();
            } catch (IOException e) {
              throw new RuntimeException("Cannot close output stream: " + e.toString(), e);
            }
          }
        }
      }
    }
}

// 创建一个名称为name的文件,返回一个输出流,以便对该文件进行写入操作
public IndexOutput createOutput(String name) throws IOException {

File file = new File(directory, name);
    if (file.exists() && !file.delete())          // 如果name指定文件存在,或者没有被删除掉,抛出异常
      throw new IOException("Cannot overwrite: " + file);

return new FSIndexOutput(file);    // 返回文件File file的一个输出流
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzjsjs.html