本文整理汇总了Java中com.google.common.io.Closer.create方法的典型用法代码示例。如果您正苦于以下问题:Java Closer.create方法的具体用法?Java Closer.create怎么用?Java Closer.create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.common.io.Closer
的用法示例。
在下文中一共展示了Closer.create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: writeToZip
import com.google.common.io.Closer; //导入方法依赖的package包/类
/**
* Write the dex program resources to @code{archive} and the proguard resource as its sibling.
*/
public void writeToZip(Path archive, OutputMode outputMode) throws IOException {
OpenOption[] options =
new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING};
try (Closer closer = Closer.create()) {
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(archive, options))) {
List<Resource> dexProgramSources = getDexProgramResources();
for (int i = 0; i < dexProgramSources.size(); i++) {
ZipEntry zipEntry = new ZipEntry(outputMode.getOutputPath(dexProgramSources.get(i), i));
byte[] bytes =
ByteStreams.toByteArray(closer.register(dexProgramSources.get(i).getStream()));
zipEntry.setSize(bytes.length);
out.putNextEntry(zipEntry);
out.write(bytes);
out.closeEntry();
}
}
}
}
示例2: 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();
}
}
示例3: main
import com.google.common.io.Closer; //导入方法依赖的package包/类
public static void main(String[] args)
throws IOException, ProguardRuleParserException, CompilationException, ExecutionException {
Command.Builder builder = Command.parse(args);
Command command = builder.build();
if (command.isPrintHelp()) {
System.out.println(Command.USAGE_MESSAGE);
return;
}
AndroidApp app = command.getInputApp();
Map<String, Integer> result = new HashMap<>();
try (Closer closer = Closer.create()) {
for (Resource resource : app.getDexProgramResources()) {
for (Segment segment: DexFileReader.parseMapFrom(closer.register(resource.getStream()))) {
int value = result.computeIfAbsent(segment.typeName(), (key) -> 0);
result.put(segment.typeName(), value + segment.size());
}
}
}
System.out.println("Segments in dex application (name: size):");
result.forEach( (key, value) -> System.out.println(" - " + key + ": " + value));
}
示例4: buildAndTreeShakeFromDeployJar
import com.google.common.io.Closer; //导入方法依赖的package包/类
@Test
public void buildAndTreeShakeFromDeployJar()
throws ExecutionException, IOException, ProguardRuleParserException, CompilationException {
int maxSize = 20000000;
AndroidApp app = runAndCheckVerification(
CompilerUnderTest.R8,
CompilationMode.RELEASE,
BASE + APK,
null,
BASE + PG_CONF,
null,
// Don't pass any inputs. The input will be read from the -injars in the Proguard
// configuration file.
ImmutableList.of());
int bytes = 0;
try (Closer closer = Closer.create()) {
for (Resource dex : app.getDexProgramResources()) {
bytes += ByteStreams.toByteArray(closer.register(dex.getStream())).length;
}
}
assertTrue("Expected max size of " + maxSize + ", got " + bytes, bytes < maxSize);
}
示例5: assertIdenticalApplications
import com.google.common.io.Closer; //导入方法依赖的package包/类
public void assertIdenticalApplications(AndroidApp app1, AndroidApp app2, boolean write)
throws IOException {
try (Closer closer = Closer.create()) {
if (write) {
app1.writeToDirectory(temp.newFolder("app1").toPath(), OutputMode.Indexed);
app2.writeToDirectory(temp.newFolder("app2").toPath(), OutputMode.Indexed);
}
List<Resource> files1 = app1.getDexProgramResources();
List<Resource> files2 = app2.getDexProgramResources();
assertEquals(files1.size(), files2.size());
for (int index = 0; index < files1.size(); index++) {
InputStream file1 = closer.register(files1.get(index).getStream());
InputStream file2 = closer.register(files2.get(index).getStream());
byte[] bytes1 = ByteStreams.toByteArray(file1);
byte[] bytes2 = ByteStreams.toByteArray(file2);
assertArrayEquals("File index " + index, bytes1, bytes2);
}
}
}
示例6: 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();
}
}
示例7: 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;
}
示例8: setUp
import com.google.common.io.Closer; //导入方法依赖的package包/类
@Before
public void setUp() {
executor = createMock(DelayExecutor.class);
clock = new FakeClock();
stateManager = createMock(StateManager.class);
storageUtil = new StorageTestUtil(this);
storageUtil.expectOperations();
shutdownCommand = createMock(Command.class);
pruner = new TaskHistoryPruner(
executor,
stateManager,
clock,
new HistoryPrunnerSettings(ONE_DAY, ONE_MINUTE, PER_JOB_HISTORY),
storageUtil.storage,
new Lifecycle(shutdownCommand));
closer = Closer.create();
}
示例9: 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;
}
}
示例10: 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;
}
}
示例11: 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();
}
示例12: 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;
}
示例13: 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);
}
}
}
示例14: close
import com.google.common.io.Closer; //导入方法依赖的package包/类
@Override
public void close() throws IOException {
// Goal: by the end of this function, both results and session are null and closed,
// independent of what errors they throw or prior state.
if (session == null) {
// Only possible when previously closed, so we know that results is also null.
return;
}
// Session does not implement Closeable -- it's AutoCloseable. So we can't register it with
// the Closer, but we can use the Closer to simplify the error handling.
try (Closer closer = Closer.create()) {
if (results != null) {
closer.register(results);
results = null;
}
session.close();
} finally {
session = null;
}
}
示例15: runProgram
import com.google.common.io.Closer; //导入方法依赖的package包/类
private int runProgram(PrintStream output, Map<Path, HashCode> digests)
throws InterruptedException {
AtomicBoolean failed = new AtomicBoolean();
try (Closer closer = Closer.create()) {
component
.newActionComponentBuilder()
.args(new ArrayList<>(arguments))
.closer(closer)
.inputDigests(digests)
.output(output)
.failed(failed)
.build()
.program()
.run();
} catch (Exception e) {
if (Utilities.wasInterrupted(e)) {
throw new InterruptedException();
}
output.printf(
"ERROR: Program threw uncaught exception with args: %s%n",
Joiner.on(' ').join(arguments));
e.printStackTrace(output);
return 1;
}
return failed.get() ? 1 : 0;
}