當前位置: 首頁>>代碼示例>>Java>>正文


Java Closeables.close方法代碼示例

本文整理匯總了Java中com.google.common.io.Closeables.close方法的典型用法代碼示例。如果您正苦於以下問題:Java Closeables.close方法的具體用法?Java Closeables.close怎麽用?Java Closeables.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.common.io.Closeables的用法示例。


在下文中一共展示了Closeables.close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: closeSource

import com.google.common.io.Closeables; //導入方法依賴的package包/類
private void closeSource(final StreamSource source)
{
    if( source != null )
    {
        try
        {
            // one of these should be non-null
            Closeables.close(source.getReader(), true);
            Closeables.close(source.getInputStream(), true);
        }
        catch( Throwable th )
        {
            // Ignore
        }
    }
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:17,代碼來源:XsltServiceImpl.java

示例2: Combiner

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public Combiner(ManifestResolver resolver, Writer output) throws IOException, XmlPullParserException
{
    this.output = output;
    this.resolver = resolver;

    Reader reader = null;
    try
    {
        reader = resolver.getStream();

        parser = new MXParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        parser.setInput(reader);

        parseXml();
    }
    finally
    {
        Closeables.close(reader, true); // Quietly
    }
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:22,代碼來源:IMSUtilities.java

示例3: createItemFromFile

import com.google.common.io.Closeables; //導入方法依賴的package包/類
private ObjectNode createItemFromFile(String jsonFile, String token, String stagingUuid, int responseCode,
    boolean returnError) throws Exception
{
    final StringWriter sw = new StringWriter();
    final InputStream input = ItemApiEditTest.class.getResourceAsStream(jsonFile);
    try
    {
        CharStreams.copy(new InputStreamReader(input), sw);
    }
    finally
    {
        Closeables.close(input, true);
    }
    String newItemJson = sw.toString();

    return createItemFromString(newItemJson, token, stagingUuid, responseCode, returnError);

}
 
開發者ID:equella,項目名稱:Equella,代碼行數:19,代碼來源:ItemApiEditTest.java

示例4: getStringValue

import com.google.common.io.Closeables; //導入方法依賴的package包/類
private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath)
        throws StreamException, XPathExpressionException {
    XPath xpath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = file.getContents();
        return xpath.evaluate(xPath, new InputSource(is));
    } finally {
        try {
            Closeables.close(is, true /* swallowIOException */);
        } catch (IOException e) {
            // cannot happen
        }
    }
}
 
開發者ID:tranleduy2000,項目名稱:javaide,代碼行數:17,代碼來源:AndroidManifest.java

示例5: createNewStore

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public static boolean createNewStore(String storeType, File storeFile, char[] storePassword, DN dn) {
    if (storeType == null) {
        storeType = "jks";
    }
    try {
        KeyStore ks = KeyStore.getInstance(storeType);
        ks.load(null, null);
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
開發者ID:NBANDROIDTEAM,項目名稱:NBANDROID-V2,代碼行數:23,代碼來源:ApkUtils.java

示例6: addNewKey

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public static boolean addNewKey(KeyStore ks, File storeFile, char[] storePassword, DN dn) {
    try {
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
開發者ID:NBANDROIDTEAM,項目名稱:NBANDROID-V2,代碼行數:18,代碼來源:ApkUtils.java

示例7: StashSplitIterator

import com.google.common.io.Closeables; //導入方法依賴的package包/類
StashSplitIterator(AmazonS3 s3, String bucket, String key) {
    InputStream rawIn = new RestartingS3InputStream(s3, bucket, key);
    try {
        // File is gzipped
        // Note:
        //   Because the content may be concatenated gzip files we cannot use the default GZIPInputStream.
        //   GzipCompressorInputStream supports concatenated gzip files.
        GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(rawIn, true);
        _in = new BufferedReader(new InputStreamReader(gzipIn, Charsets.UTF_8));
        // Create a line reader
        _reader = new LineReader(_in);
    } catch (Exception e) {
        try {
            Closeables.close(rawIn, true);
        } catch (IOException ignore) {
            // Won't happen, already caught and logged
        }
        throw Throwables.propagate(e);
    }
}
 
開發者ID:bazaarvoice,項目名稱:emodb,代碼行數:21,代碼來源:StashSplitIterator.java

示例8: testPipelined

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public void testPipelined() {// 0.076秒
    Jedis jedis = new Jedis("120.25.241.144", 6379);
    jedis.auth("b840fc02d52404542994");

    long start = System.currentTimeMillis();
    Pipeline pipeline = jedis.pipelined();
    for (int i = 0; i < 1000; i++) {
        pipeline.set("n" + i, "n" + i);
        System.out.println(i);
    }
    pipeline.syncAndReturnAll();
    long end = System.currentTimeMillis();
    System.out.println("共花費:" + (end - start) / 1000.0 + "秒");

    jedis.disconnect();
    try {
        Closeables.close(jedis, true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:xiangxik,項目名稱:java-platform,代碼行數:22,代碼來源:RedisExample.java

示例9: StashRowIterable

import com.google.common.io.Closeables; //導入方法依賴的package包/類
/**
 * In order to fail fast create the initial iterator on instantiation.  This way exceptions such as
 * TableNotStashedException will be thrown immediately and not deferred until the first iteration.
 */
public StashRowIterable() {
    _initialIterator = createStashRowIterator();
    // Force the first record to be evaluated by calling hasNext()
    try {
        _initialIterator.hasNext();
        _openIterators.add(_initialIterator);
    } catch (Exception e) {
        try {
            Closeables.close(_initialIterator, true);
        } catch (IOException e2) {
            // Already caught and logged
        }
        throw Throwables.propagate(e);
    }
}
 
開發者ID:bazaarvoice,項目名稱:emodb,代碼行數:20,代碼來源:StashRowIterable.java

示例10: toCqlScript

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public String toCqlScript() {
    try {
        final InputStream cqlStream = CreateKeyspacesCommand.class.getResourceAsStream(_templateResourceName);
        if (cqlStream == null) {
            throw new IllegalStateException("couldn't find " + _templateResourceName + " in classpath");
        }
        String cql;
        try {
            cql = CharStreams.toString(new InputStreamReader(cqlStream, "UTF-8"));
        } finally {
            Closeables.close(cqlStream, true);
        }
        // replace bindings
        for (Map.Entry<String, String> binding : _bindings.entrySet()) {
            cql = cql.replace("${" + binding.getKey() + "}", binding.getValue());
        }
        return cql;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:bazaarvoice,項目名稱:emodb,代碼行數:22,代碼來源:CqlTemplate.java

示例11: testShardNormal

import com.google.common.io.Closeables; //導入方法依賴的package包/類
public void testShardNormal() {// 13.619秒
    JedisShardInfo jedis = new JedisShardInfo("120.25.241.144", 6379);
    jedis.setPassword("b840fc02d52404542994");

    List<JedisShardInfo> shards = Arrays.asList(jedis);
    ShardedJedis sharding = new ShardedJedis(shards);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000; i++) {
        sharding.set("n" + i, "n" + i);
        System.out.println(i);
    }
    long end = System.currentTimeMillis();
    System.out.println("共花費:" + (end - start) / 1000.0 + "秒");

    sharding.disconnect();
    try {
        Closeables.close(sharding, true);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:xiangxik,項目名稱:java-platform,代碼行數:23,代碼來源:RedisExample.java

示例12: writeSnapshot

import com.google.common.io.Closeables; //導入方法依賴的package包/類
@Override
public void writeSnapshot(TransactionSnapshot snapshot) throws IOException {
  // save the snapshot to a temporary file
  File snapshotTmpFile = new File(snapshotDir, TMP_SNAPSHOT_FILE_PREFIX + snapshot.getTimestamp());
  LOG.debug("Writing snapshot to temporary file {}", snapshotTmpFile);
  OutputStream out = Files.newOutputStreamSupplier(snapshotTmpFile).getOutput();
  boolean threw = true;
  try {
    codecProvider.encode(out, snapshot);
    threw = false;
  } finally {
    Closeables.close(out, threw);
  }

  // move the temporary file into place with the correct filename
  File finalFile = new File(snapshotDir, SNAPSHOT_FILE_PREFIX + snapshot.getTimestamp());
  if (!snapshotTmpFile.renameTo(finalFile)) {
    throw new IOException("Failed renaming temporary snapshot file " + snapshotTmpFile.getName() + " to " +
        finalFile.getName());
  }

  LOG.debug("Completed snapshot to file {}", finalFile);
}
 
開發者ID:apache,項目名稱:incubator-tephra,代碼行數:24,代碼來源:LocalFileTransactionStateStorage.java

示例13: setNextKeyValue

import com.google.common.io.Closeables; //導入方法依賴的package包/類
/**
 * Read the next row from the split, storing the coordinate in "key" and the content in "value".  If there are no
 * more rows then false is returned and "key" and "value" are not modified.
 * @return true if a row was read, false if there were no more rows
 */
public boolean setNextKeyValue(Text key, Row value)
        throws IOException {
    if (!_rows.hasNext()) {
        Closeables.close(this, true);
        return false;
    }

    try {
        Map<String, Object> content = _rows.next();
        key.set(Coordinate.fromJson(content).toString());
        value.set(content);
        _rowsRead += 1;
    } catch (Exception e) {
        for (Throwable cause : Throwables.getCausalChain(e)) {
            Throwables.propagateIfInstanceOf(cause, IOException.class);
        }
        throw new IOException("Failed to read next row", e);
    }
    return true;
}
 
開發者ID:bazaarvoice,項目名稱:emodb,代碼行數:26,代碼來源:BaseRecordReader.java

示例14: readTestFile

import com.google.common.io.Closeables; //導入方法依賴的package包/類
@SuppressWarnings("resource")
protected String readTestFile(String relativePath, boolean expectExists) throws IOException {
    InputStream stream = getTestResource(relativePath, expectExists);
    if (expectExists) {
        assertNotNull(relativePath + " does not exist", stream);
    } else if (stream == null) {
        return null;
    }

    String xml = new String(ByteStreams.toByteArray(stream), Charsets.UTF_8);
    try {
        Closeables.close(stream, true /* swallowIOException */);
    } catch (IOException e) {
        // cannot happen
    }

    assertTrue(xml.length() > 0);

    // Remove any references to the project name such that we are isolated from
    // that in golden file.
    // Appears in strings.xml etc.
    xml = removeSessionData(xml);

    return xml;
}
 
開發者ID:jskierbi,項目名稱:intellij-ce-playground,代碼行數:26,代碼來源:SdkTestCase.java

示例15: advanceToNextPage

import com.google.common.io.Closeables; //導入方法依賴的package包/類
private void advanceToNextPage() {
  synchronized (this) {
    int nextIdx = dataPages.indexOf(currentPage) + 1;
    if (destructive && currentPage != null) {
      dataPages.remove(currentPage);
      freePage(currentPage);
      nextIdx --;
    }
    if (dataPages.size() > nextIdx) {
      currentPage = dataPages.get(nextIdx);
      pageBaseObject = currentPage.getBaseObject();
      offsetInPage = currentPage.getBaseOffset();
      recordsInPage = Platform.getInt(pageBaseObject, offsetInPage);
      offsetInPage += 4;
    } else {
      currentPage = null;
      if (reader != null) {
        // remove the spill file from disk
        File file = spillWriters.removeFirst().getFile();
        if (file != null && file.exists()) {
          if (!file.delete()) {
            logger.error("Was unable to delete spill file {}", file.getAbsolutePath());
          }
        }
      }
      try {
        Closeables.close(reader, /* swallowIOException = */ false);
        if(spillWriters.size()>0) {
          reader = spillWriters.getFirst().getReader(serializerManager);
        }
        recordsInPage = -1;

      } catch (IOException e) {
        // Scala iterator does not handle exception
        Platform.throwException(e);
      }
    }
  }
}
 
開發者ID:huang-up,項目名稱:mycat-src-1.6.1-RELEASE,代碼行數:40,代碼來源:BytesToBytesMap.java


注:本文中的com.google.common.io.Closeables.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。