当前位置: 首页>>代码示例>>Java>>正文


Java Closer.close方法代码示例

本文整理汇总了Java中com.google.common.io.Closer.close方法的典型用法代码示例。如果您正苦于以下问题:Java Closer.close方法的具体用法?Java Closer.close怎么用?Java Closer.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.common.io.Closer的用法示例。


在下文中一共展示了Closer.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: zipDirectory

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Zips an entire directory specified by the path.
 *
 * @param sourceDirectory the directory to read from. This directory and all
 *     subdirectories will be added to the zip-file. The path within the zip
 *     file is relative to the directory given as parameter, not absolute.
 * @param zipFile the zip-file to write to.
 * @throws IOException the zipping failed, e.g. because the input was not
 *     readable.
 */
static void zipDirectory(
    File sourceDirectory,
    File zipFile) throws IOException {
  checkNotNull(sourceDirectory);
  checkNotNull(zipFile);
  checkArgument(
      sourceDirectory.isDirectory(),
      "%s is not a valid directory",
      sourceDirectory.getAbsolutePath());
  checkArgument(
      !zipFile.exists(),
      "%s does already exist, files are not being overwritten",
      zipFile.getAbsolutePath());
  Closer closer = Closer.create();
  try {
    OutputStream outputStream = closer.register(new BufferedOutputStream(
        new FileOutputStream(zipFile)));
    zipDirectory(sourceDirectory, outputStream);
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
开发者ID:spotify,项目名称:hype,代码行数:35,代码来源:ZipFiles.java

示例2: writeSelfReferencingJarFile

import com.google.common.io.Closer; //导入方法依赖的package包/类
private static void writeSelfReferencingJarFile(File jarFile, String... entries)
    throws IOException {
  Manifest manifest = new Manifest();
  // Without version, the manifest is silently ignored. Ugh!
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, jarFile.getName());

  Closer closer = Closer.create();
  try {
    FileOutputStream fileOut = closer.register(new FileOutputStream(jarFile));
    JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut));
    for (String entry : entries) {
      jarOut.putNextEntry(new ZipEntry(entry));
      Resources.copy(ClassPathTest.class.getResource(entry), jarOut);
      jarOut.closeEntry();
    }
  } catch (Throwable e) {
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:23,代码来源:ClassPathTest.java

示例3: loadProperties

import com.google.common.io.Closer; //导入方法依赖的package包/类
@Override
@NonNull
public Properties loadProperties(@NonNull File file) {
    Properties props = new Properties();
    Closer closer = Closer.create();
    try {
        FileInputStream fis = closer.register(new FileInputStream(file));
        props.load(fis);
    } catch (IOException ignore) {
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
        }
    }
    return props;
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:18,代码来源:FileOp.java

示例4: create

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred.
 */
@Override public Session create(Cassandra3Storage cassandra) {
  Closer closer = Closer.create();
  try {
    Cluster cluster = closer.register(buildCluster(cassandra));
    cluster.register(new QueryLogger.Builder().build());
    Session session;
    if (cassandra.ensureSchema) {
      session = closer.register(cluster.connect());
      Schema.ensureExists(cassandra.keyspace, session);
      session.execute("USE " + cassandra.keyspace);
    } else {
      session = cluster.connect(cassandra.keyspace);
    }

    initializeUDTs(session);

    return session;
  } catch (RuntimeException e) {
    try {
      closer.close();
    } catch (IOException ignored) {
    }
    throw e;
  }
}
 
开发者ID:liaominghua,项目名称:zipkin,代码行数:30,代码来源:DefaultSessionFactory.java

示例5: create

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Creates a session and ensures schema if configured. Closes the cluster and session if any
 * exception occurred.
 */
@Override public Session create(CassandraStorage cassandra) {
  Closer closer = Closer.create();
  try {
    Cluster cluster = closer.register(buildCluster(cassandra));
    cluster.register(new QueryLogger.Builder().build());
    if (cassandra.ensureSchema) {
      Session session = closer.register(cluster.connect());
      Schema.ensureExists(cassandra.keyspace, session);
      session.execute("USE " + cassandra.keyspace);
      return session;
    } else {
      return cluster.connect(cassandra.keyspace);
    }
  } catch (RuntimeException e) {
    try {
      closer.close();
    } catch (IOException ignored) {
    }
    throw e;
  }
}
 
开发者ID:liaominghua,项目名称:zipkin,代码行数:26,代码来源:SessionFactory.java

示例6: compress

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Deflater 压缩
 *
 * @param content
 * @return
 */
public static byte[] compress(String content) {
    Closer closer = Closer.create();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true);
    try {
        DeflaterOutputStream out = closer.register(new DeflaterOutputStream(byteArrayOutputStream, deflater));
        out.write(content.getBytes(Charsets.UTF_8.name()));
    } catch (Exception e) {
        logger.error(String.format("compress error:"), e);
    } finally {
        if (closer != null)
            try {
                closer.close();
            } catch (Exception ex) {
                logger.info(String.format("compress error,close the stream error:"), ex);
            }
    }
    deflater.end();
    return byteArrayOutputStream.toByteArray();
}
 
开发者ID:glameyzhou,项目名称:scaffold,代码行数:27,代码来源:CompressHandler.java

示例7: decompress

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
     * inflater 解压
     *
     * @param inputStream
     * @return
     */
    public static byte[] decompress(InputStream inputStream) {
        Closer closer = Closer.create();
        try {
            BufferedInputStream bufferInputStream = closer.register(new BufferedInputStream(new InflaterInputStream(inputStream, new Inflater(true))));
//			bufferInputStream = closer.register(new BufferedInputStream(new GZIPInputStream(inputStream)));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ByteStreams.copy(bufferInputStream, byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            logger.error(String.format("decompress error:"), e);
        } finally {
            try {
                if (closer != null) {
                    closer.close();
                }
            } catch (Exception e1) {
                logger.error(String.format("decompress error,close the stream error"), e1);
            }
        }
        return null;
    }
 
开发者ID:glameyzhou,项目名称:scaffold,代码行数:28,代码来源:CompressHandler.java

示例8: streamAndCompressInput

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Read data from the original input stream and pipe it to the compressing stream until fully read.
 */
private void streamAndCompressInput() {
    try {
        byte[] newline = "\n".getBytes(Charsets.UTF_8);
        while (!_closed && fetchNextRow()) {
            _rawOut.write(_buffer.array(), 0, _buffer.limit());
            _rawOut.write(newline);
        }
        _rawOut.close();
    } catch (Exception e) {
        try {
            Closer closer = Closer.create();
            closer.register(_rawOut);
            closer.register(_gzipIn);
            closer.close();
        } catch (IOException ignore) {
            // Ignore exceptions closing, don't mask the original exception.
        }
        if (!_closed) {
            _inputException = e instanceof IOException ? (IOException ) e : new IOException(e);
        }
    }
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:26,代码来源:EmoFileSystem.java

示例9: readServiceFile

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Reads the set of service classes from a service file.
 *
 * @param input not {@code null}. Closed after use.
 * @return a not {@code null Set} of service class names.
 * @throws IOException
 */
static Set<String> readServiceFile(InputStream input) throws IOException {
  HashSet<String> serviceClasses = new HashSet<String>();
  Closer closer = Closer.create();
  try {
    // TODO(gak): use CharStreams
    BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, Charsets.UTF_8)));
    String line;
    while ((line = r.readLine()) != null) {
      int commentStart = line.indexOf('#');
      if (commentStart >= 0) {
        line = line.substring(0, commentStart);
      }
      line = line.trim();
      if (!line.isEmpty()) {
        serviceClasses.add(line);
      }
    }
    return serviceClasses;
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
开发者ID:jfunktor,项目名称:RxFunktor,代码行数:32,代码来源:ServicesFiles.java

示例10: addLocalResources

import com.google.common.io.Closer; //导入方法依赖的package包/类
/** Returns a URL to a local copy of the given resource, or null. There is
 * no filename conflict resolution. */
protected String addLocalResources(URL url) throws IOException {
    // Attempt to make local copy
    File resourceDir = computeResourceDir();
    if (resourceDir != null) {
        String base = url.getFile();
        base = base.substring(base.lastIndexOf('/') + 1);
        mNameToFile.put(base, new File(url.toExternalForm()));

        File target = new File(resourceDir, base);
        Closer closer = Closer.create();
        try {
            FileOutputStream output = closer.register(new FileOutputStream(target));
            InputStream input = closer.register(url.openStream());
            ByteStreams.copy(input, output);
        } catch (Throwable e) {
            closer.rethrow(e);
        } finally {
            closer.close();
        }
        return resourceDir.getName() + '/' + encodeUrl(base);
    }
    return null;
}
 
开发者ID:jskierbi,项目名称:intellij-ce-playground,代码行数:26,代码来源:Reporter.java

示例11: createRealJarArchive

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * We need real Jar contents as this test will actually run Gradle that will peek inside the archive.
 */
@NotNull
private static byte[] createRealJarArchive() throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  Closer closer = Closer.create();
  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream jar = closer.register(new JarOutputStream(buffer, manifest));
  try {
    jar.putNextEntry(new JarEntry("/dummy.txt"));
    jar.write(TOP_LEVEL_BUILD_GRADLE.getBytes());
    closer.close();
    return buffer.toByteArray();
  }
  catch (IOException e) {
    closer.close();
    throw closer.rethrow(e);
  }
}
 
开发者ID:jskierbi,项目名称:intellij-ce-playground,代码行数:22,代码来源:WrapArchiveWizardPathTest.java

示例12: put

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * See {@link StateStore#put(String, String, T)}.
 *
 * <p>
 *   This implementation does not support putting the state object into an existing store as
 *   append is to be supported by the Hadoop SequenceFile (HADOOP-7139).
 * </p>
 */
@Override
public void put(String storeName, String tableName, T state)
    throws IOException {
  Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
  if (!this.fs.exists(tablePath) && !create(storeName, tableName)) {
    throw new IOException("Failed to create a state file for table " + tableName);
  }

  Closer closer = Closer.create();
  try {
    SequenceFile.Writer writer =
        closer.register(SequenceFile.createWriter(this.fs, this.conf, tablePath, Text.class, this.stateClass,
            SequenceFile.CompressionType.BLOCK, new DefaultCodec()));
    writer.append(new Text(Strings.nullToEmpty(state.getId())), state);
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
开发者ID:Hanmourang,项目名称:Gobblin,代码行数:29,代码来源:FsStateStore.java

示例13: getSecurityTokens

import com.google.common.io.Closer; //导入方法依赖的package包/类
private ByteBuffer getSecurityTokens() throws IOException {
  Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
  Closer closer = Closer.create();
  try {
    DataOutputBuffer dataOutputBuffer = closer.register(new DataOutputBuffer());
    credentials.writeTokenStorageToStream(dataOutputBuffer);

    // Remove the AM->RM token so that containers cannot access it
    Iterator<Token<?>> tokenIterator = credentials.getAllTokens().iterator();
    while (tokenIterator.hasNext()) {
      Token<?> token = tokenIterator.next();
      if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
        tokenIterator.remove();
      }
    }

    return ByteBuffer.wrap(dataOutputBuffer.getData(), 0, dataOutputBuffer.getLength());
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
开发者ID:Hanmourang,项目名称:Gobblin,代码行数:24,代码来源:YarnService.java

示例14: getTokenFromSeqFile

import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
 * Get token from the token sequence file.
 * @param authPath
 * @param proxyUserName
 * @return Token for proxyUserName if it exists.
 * @throws IOException
 */
private Optional<Token> getTokenFromSeqFile(String authPath, String proxyUserName) throws IOException {
  Closer closer = Closer.create();
  try {
    FileSystem localFs = FileSystem.getLocal(new Configuration());
    SequenceFile.Reader tokenReader =
        closer.register(new SequenceFile.Reader(localFs, new Path(authPath), localFs.getConf()));
    Text key = new Text();
    Token value = new Token();
    while (tokenReader.next(key, value)) {
      LOG.info("Found token for " + key);
      if (key.toString().equals(proxyUserName)) {
        return Optional.of(value);
      }
    }
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
  return Optional.absent();
}
 
开发者ID:Hanmourang,项目名称:Gobblin,代码行数:29,代码来源:ProxiedFileSystemWrapper.java

示例15: saveProperties

import com.google.common.io.Closer; //导入方法依赖的package包/类
@Override
public void saveProperties(
        @NonNull File file,
        @NonNull Properties props,
        @NonNull String comments) throws IOException {
    Closer closer = Closer.create();
    try {
        OutputStream fos = closer.register(newFileOutputStream(file));
        props.store(fos, comments);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:16,代码来源:FileOp.java


注:本文中的com.google.common.io.Closer.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。