org.apache.commons.io.IOUtils.closeQuietly()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(11.1k)|赞(0)|评价(0)|浏览(830)

本文整理了Java中org.apache.commons.io.IOUtils.closeQuietly()方法的一些代码示例,展示了IOUtils.closeQuietly()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。IOUtils.closeQuietly()方法的具体详情如下:
包路径:org.apache.commons.io.IOUtils
类名称:IOUtils
方法名:closeQuietly

IOUtils.closeQuietly介绍

[英]Unconditionally close a Closeable.

Equivalent to Closeable#close(), except any exceptions will be ignored. This is typically used in finally blocks.

Example code:

Closeable closeable = null; 
try { 
closeable = new FileReader("foo.txt"); 
// process closeable 
closeable.close(); 
} catch (Exception e) { 
// error handling 
} finally { 
IOUtils.closeQuietly(closeable); 
}

[中]无条件关闭Closeable
与Closeable#close()等效,但任何异常都将被忽略。这通常用于finally块。
示例代码:

Closeable closeable = null; 
try { 
closeable = new FileReader("foo.txt"); 
// process closeable 
closeable.close(); 
} catch (Exception e) { 
// error handling 
} finally { 
IOUtils.closeQuietly(closeable); 
}

代码示例

代码示例来源:origin: iBotPeaches/Apktool

public static void copyAndClose(InputStream in, OutputStream out)
    throws IOException {
  try {
    IOUtils.copy(in, out);
  } finally {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
  }
}

代码示例来源:origin: gocd/gocd

public void streamToFile(InputStream stream, File dest) throws IOException {
  dest.getParentFile().mkdirs();
  FileOutputStream out = new FileOutputStream(dest, true);
  try {
    IOUtils.copyLarge(stream, out);
  } finally {
    IOUtils.closeQuietly(out);
  }
}

代码示例来源:origin: alibaba/jstorm

private static String readContent(String filePath) throws IOException {
  DataInputStream ds = null;
  try {
    ds = new DataInputStream(new FileInputStream(filePath));
    return ds.readUTF();
  } finally {
    org.apache.commons.io.IOUtils.closeQuietly(ds);
  }
}

代码示例来源:origin: square/spoon

private static void copyStaticToOutput(String resource, File output) {
  InputStream is = null;
  OutputStream os = null;
  try {
   is = HtmlRenderer.class.getResourceAsStream("/static/" + resource);
   os = new FileOutputStream(new File(output, resource));
   IOUtils.copy(is, os);
  } catch (IOException e) {
   throw new RuntimeException("Unable to copy static resource " + resource + " to " + output, e);
  } finally {
   IOUtils.closeQuietly(is);
   IOUtils.closeQuietly(os);
  }
 }
}

代码示例来源:origin: apache/incubator-pinot

LOGGER.debug(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
  if (!outputFile.exists()) {
   LOGGER.debug(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath()));
   if (!outputFile.mkdirs()) {
    throw new IllegalStateException(
  LOGGER.debug(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
  File directory = outputFile.getParentFile();
  if (!directory.exists()) {
   directory.mkdirs();
   outputFileStream = new FileOutputStream(outputFile);
   IOUtils.copy(debInputStream, outputFileStream);
  } finally {
   IOUtils.closeQuietly(outputFileStream);
IOUtils.closeQuietly(debInputStream);
IOUtils.closeQuietly(is);

代码示例来源:origin: deeplearning4j/nd4j

File target = new File(file);
if (!target.exists())
  throw new IllegalArgumentException("Archive doesnt exist");
FileInputStream fin = new FileInputStream(target);
int BUFFER = 2048;
byte data[] = new byte[BUFFER];
      File newFile = new File(dest + File.separator + fileName);
      FileOutputStream fos = new FileOutputStream(newFile);
      log.debug("File extracted: " + newFile.getAbsoluteFile());
      File f = new File(dest + File.separator + entry.getName());
      f.mkdirs();
      try(FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
        BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);) {
        while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
        IOUtils.closeQuietly(destStream);
} else if (file.endsWith(".gz")) {
  File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
  if (extracted.exists())
    extracted.delete();
  extracted.createNewFile();

代码示例来源:origin: SonarSource/sonarqube

static Props loadPropsFromCommandLineArgs(String[] args) {
  if (args.length != 1) {
   throw new IllegalArgumentException("Only a single command-line argument is accepted " +
    "(absolute path to configuration file)");
  }

  File propertyFile = new File(args[0]);
  Properties properties = new Properties();
  Reader reader = null;
  try {
   reader = new InputStreamReader(new FileInputStream(propertyFile), StandardCharsets.UTF_8);
   properties.load(reader);
  } catch (Exception e) {
   throw new IllegalStateException("Could not read properties from file: " + args[0], e);
  } finally {
   IOUtils.closeQuietly(reader);
   deleteQuietly(propertyFile);
  }
  return new Props(properties);
 }
}

代码示例来源:origin: plutext/docx4j

/**
 * Retrieve the last modified date/time of a URL.
 * @param url the URL
 * @return the last modified date/time
 */
public static long getLastModified(URL url) {
  try {
    URLConnection conn = url.openConnection();
    try {
      return conn.getLastModified();
    } finally {
      //An InputStream is created even if it's not accessed, but we need to close it.
      IOUtils.closeQuietly(conn.getInputStream());
    }
  } catch (IOException e) {
    // Should never happen, because URL must be local
    log.debug("IOError: " + e.getMessage());
    return 0;
  }
}

代码示例来源:origin: apache/hive

out = null;
} finally {
 IOUtils.closeQuietly(out);
  + " " + isSilent + " " + hiveConfArgs;
String workDir = (new File(".")).getCanonicalPath();
String files = Utilities.getResourceFiles(conf, SessionState.ResourceType.FILE);
 if (!(new File(workDir)).mkdir()) {
  throw new IOException("Cannot create tmp working dir: " + workDir);
LOG.debug("setting HADOOP_USER_NAME\t" + endUserName);
variables.put("HADOOP_USER_NAME", endUserName);
 String value = entry.getValue();
 env[pos++] = name + "=" + value;
 LOG.debug("Setting env: " + name + "=" + LogUtils.maskIfPassword(name, value));
executor = Runtime.getRuntime().exec(cmdLine, env, new File(workDir));

代码示例来源:origin: gocd/gocd

private void extractTo(ZipEntry entry, InputStream entryInputStream, File toDir) throws IOException {
  String entryName = nonRootedEntryName(entry);
  File outputFile = new File(toDir, entryName);
  if (isDirectory(entryName)) {
    outputFile.mkdirs();
    return;
  }
  FileOutputStream os = null;
  try {
    os = new FileOutputStream(outputFile);
    int bytes;
    while ((bytes = entryInputStream.read(fileBuffer)) > 0) {
      os.write(fileBuffer, 0, bytes);
    }
  } catch (IOException e) {
    throw e;
  } finally {
    IOUtils.closeQuietly(os);
  }
}

代码示例来源:origin: apache/usergrid

OutputStream os = null;
try {
  os = new BufferedOutputStream( new FileOutputStream( tempFile.getAbsolutePath() ) );
  IOUtils.closeQuietly( os );
FileInputStream chunk = new FileInputStream(tempFile);
  listResult = getS3Client().listMultipartUploads( listRequest );
  if (logger.isDebugEnabled()) {
    logger.debug("Files that haven't been aborted are: {}", listResult.getMultipartUploads().listIterator().toString());

代码示例来源:origin: k9mail/k-9

private static void copyFile(File from, File to) throws IOException {
  FileInputStream in = new FileInputStream(from);
  FileOutputStream out = new FileOutputStream(to);
  try {
    byte[] buffer = new byte[1024];
    int count;
    while ((count = in.read(buffer)) > 0) {
      out.write(buffer, 0, count);
    }
    out.close();
  } finally {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
  }
}

代码示例来源:origin: alibaba/jvm-sandbox

private static Properties fetchProperties(final String propertiesFilePath) {
  final Properties properties = new Properties();
  InputStream is = null;
  try {
    is = FileUtils.openInputStream(new File(propertiesFilePath));
    properties.load(is);
  } catch (Throwable cause) {
    // cause.printStackTrace(System.err);
  } finally {
    IOUtils.closeQuietly(is);
  }
  return properties;
}

代码示例来源:origin: commons-io/commons-io

protected void createFile(final File file, final long size)
  throws IOException {
  if (!file.getParentFile().exists()) {
    throw new IOException("Cannot create file " + file
        + " as the parent directory does not exist");
  }
  try (final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(file))) {
    TestUtils.generateTestData(output, size);
  }
  // try to make sure file is found
  // (to stop continuum occasionally failing)
  RandomAccessFile reader = null;
  try {
    while (reader == null) {
      try {
        reader = new RandomAccessFile(file.getPath(), "r");
      } catch (final FileNotFoundException ignore) {
      }
      try {
        TestUtils.sleep(200L);
      } catch (final InterruptedException ignore) {
        // ignore
      }
    }
  } finally {
    IOUtils.closeQuietly(reader);
  }
}

代码示例来源:origin: apache/kylin

public void spill() throws IOException {
  if(spillBuffer == null) return;
  OutputStream ops = new FileOutputStream(dumpedFile);
  InputStream ips = new ByteArrayInputStream(spillBuffer);
  IOUtils.copy(ips, ops);
  spillBuffer = null;
  IOUtils.closeQuietly(ips);
  IOUtils.closeQuietly(ops);
  logger.info("Spill buffer to disk, location: {}, size = {}.", dumpedFile.getAbsolutePath(),
    dumpedFile.length());
}

代码示例来源:origin: gocd/gocd

private File mergeAllTestResultToSingleFile(File[] allTestFiles) throws IOException {
  FileOutputStream mergedResourcesStream = null;
  try {
    File mergedResource = TestFileUtil.createUniqueTempFile("mergedFile.xml");
    mergedResourcesStream = new FileOutputStream(mergedResource);
    merge(allTestFiles, mergedResourcesStream);
    return mergedResource;
  } finally {
    IOUtils.closeQuietly(mergedResourcesStream);
  }
}

代码示例来源:origin: gocd/gocd

public void handle(InputStream stream) throws IOException {
  FileOutputStream fileOutputStream = null;
  try {
    fileOutputStream = FileUtils.openOutputStream(artifact);
    LOG.info("[Artifact File Download] [{}] Download of artifact {} started", new Date(), artifact.getName());
    IOUtils.copyLarge(stream, fileOutputStream);
    LOG.info("[Artifact File Download] [{}] Download of artifact {} ended", new Date(), artifact.getName());
  } finally {
    IOUtils.closeQuietly(fileOutputStream);
  }
  FileInputStream inputStream = null;
  try {
    inputStream = new FileInputStream(artifact);
    LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} started", new Date(), artifact.getName());
    String artifactMD5 = md5Hex(inputStream);
    new ChecksumValidator(artifactMd5Checksums).validate(srcFile, artifactMD5, checksumValidationPublisher);
    LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} ended", new Date(), artifact.getName());
  } finally {
    IOUtils.closeQuietly(inputStream);
  }
}

代码示例来源:origin: k9mail/k-9

private static void writeUriContentToTempFileIfNotExists(Context context, Uri uri, File tempFile)
    throws IOException {
  synchronized (tempFileWriteMonitor) {
    if (tempFile.exists()) {
      return;
    }
    FileOutputStream outputStream = new FileOutputStream(tempFile);
    InputStream inputStream = context.getContentResolver().openInputStream(uri);
    if (inputStream == null) {
      throw new IOException("Failed to resolve content at uri: " + uri);
    }
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
    IOUtils.closeQuietly(inputStream);
  }
}

代码示例来源:origin: azkaban/azkaban

private void runTableScripts(final Connection conn, final String table)
  throws IOException, SQLException {
 logger.info("Creating new table " + table);
 final String dbSpecificScript = "create." + table + ".sql";
 final File script = new File(this.scriptPath, dbSpecificScript);
 BufferedInputStream buff = null;
 try {
  buff = new BufferedInputStream(new FileInputStream(script));
  final String queryStr = IOUtils.toString(buff);
  final String[] splitQuery = queryStr.split(";\\s*\n");
  final QueryRunner runner = new QueryRunner();
  for (final String query : splitQuery) {
   runner.update(conn, query);
  }
  conn.commit();
 } finally {
  IOUtils.closeQuietly(buff);
 }
}

代码示例来源:origin: apache/nifi

@Override
public void close() throws IOException {
  this.closed = true;
  CommsSession commsSession;
  while ((commsSession = queue.poll()) != null) {
    try (final DataOutputStream dos = new DataOutputStream(commsSession.getOutputStream())) {
      dos.writeUTF("close");
      dos.flush();
    } catch (final IOException e) {
    }
    IOUtils.closeQuietly(commsSession);
  }
  if (logger.isDebugEnabled() && getIdentifier() != null) {
    logger.debug("Closed {}", new Object[]{getIdentifier()});
  }
}

相关文章