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


Java Closeables類代碼示例

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


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

示例1: readFromResource

import com.google.common.io.Closeables; //導入依賴的package包/類
public static String readFromResource(String resource) throws IOException {
    InputStream in = null;
    try {
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
        if (in == null) {
            in = Utils.class.getResourceAsStream(resource);
        }

        if (in == null) {
            return null;
        }

        String text = Utils.read(in);
        return text;
    } finally {
        Closeables.closeQuietly(in);
    }
}
 
開發者ID:yrain,項目名稱:smart-cache,代碼行數:19,代碼來源:Utils.java

示例2: findClassInJarFile

import com.google.common.io.Closeables; //導入依賴的package包/類
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException {
    URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName);
    String internalClassName = classUri.getPath().substring(1);
    JarFile jarFile = null;
    try {
        for (int i = 0; i < jarFiles.size(); i++) {
            jarFile = jarFiles.get(i);
            JarEntry jarEntry = jarFile.getJarEntry(internalClassName);
            if (jarEntry != null) {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    byte[] byteCode = new byte[(int) jarEntry.getSize()];
                    ByteStreams.read(inputStream, byteCode, 0, byteCode.length);
                    return defineClass(qualifiedClassName, byteCode, 0, byteCode.length);
                } finally {
                    Closeables.closeQuietly(inputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e);
    }
    return null;
}
 
開發者ID:twosigma,項目名稱:beaker-notebook-archive,代碼行數:25,代碼來源:SimpleClassLoader.java

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: getTable

import com.google.common.io.Closeables; //導入依賴的package包/類
/**
 * @see org.alfasoftware.morf.metadata.Schema#getTable(java.lang.String)
 */
@Override
public Table getTable(String name) {
  // Read the meta data for the specified table
  InputStream inputStream = xmlStreamProvider.openInputStreamForTable(name);
  try {
    XMLStreamReader xmlStreamReader = openPullParser(inputStream);
    XmlPullProcessor.readTag(xmlStreamReader, XmlDataSetNode.TABLE_NODE);

    String version = xmlStreamReader.getAttributeValue(XmlDataSetNode.URI, XmlDataSetNode.VERSION_ATTRIBUTE);
    if (StringUtils.isNotEmpty(version)) {
      return new PullProcessorTableMetaData(xmlStreamReader, Integer.parseInt(version));
    } else {
      return new PullProcessorTableMetaData(xmlStreamReader, 1);
    }
  } finally {
    // abandon any remaining content
    Closeables.closeQuietly(inputStream);
  }
}
 
開發者ID:alfasoftware,項目名稱:morf,代碼行數:23,代碼來源:XmlDataSetProducer.java

示例10: getMovies

import com.google.common.io.Closeables; //導入依賴的package包/類
public static Map<Long, String> getMovies(String base) {
    Map<Long, String> movies = new HashMap<>();
    try {
        File file = new File(base + "hot_movies.csv");
        FileLineIterator iterator = new FileLineIterator(file, false);
        String line = iterator.next();
        while (!line.isEmpty()) {
            String[] m = line.split(",");
            movies.put(Long.parseLong(m[0]), m[2]);
            line = iterator.next();
        }
        Closeables.close(iterator, true);
    } catch (Exception ex) {
    }
    return movies;
}
 
開發者ID:smallnest,項目名稱:mahout-douban-recommender,代碼行數:17,代碼來源:DoubanUserBasedRecommender.java

示例11: write

import com.google.common.io.Closeables; //導入依賴的package包/類
@Override
public OutputStream write(String entry) throws IOException {
    saveInputFile();
    File file = changedEntries.get(entry);
    if (file == null) {
        file = new File(changedFiles, entry);
        createParentDirs(file);
        changedEntries.put(entry, file);
    }
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    Closeables.close(outputStreams.put(entry, out), true);
    if (removedEntries.remove(entry)) {
        deleteIfExists(new File(removedFiles, entry).toPath());
    }
    return out;
}
 
開發者ID:ReplayMod,項目名稱:ReplayStudio,代碼行數:17,代碼來源:ZipReplayFile.java

示例12: saveTo

import com.google.common.io.Closeables; //導入依賴的package包/類
@Override
public void saveTo(File target) throws IOException {
    for (OutputStream out : outputStreams.values()) {
        Closeables.close(out, false);
    }
    outputStreams.clear();

    try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)))) {
        if (zipFile != null) {
            for (ZipEntry entry : Collections.list(zipFile.entries())) {
                if (!changedEntries.containsKey(entry.getName()) && !removedEntries.contains(entry.getName())) {
                    out.putNextEntry(entry);
                    Utils.copy(zipFile.getInputStream(entry), out);
                }
            }
        }
        for (Map.Entry<String, File> e : changedEntries.entrySet()) {
            out.putNextEntry(new ZipEntry(e.getKey()));
            Utils.copy(new BufferedInputStream(new FileInputStream(e.getValue())), out);
        }
    }
}
 
開發者ID:ReplayMod,項目名稱:ReplayStudio,代碼行數:23,代碼來源:ZipReplayFile.java

示例13: dumpBindingsToFile

import com.google.common.io.Closeables; //導入依賴的package包/類
private void dumpBindingsToFile(
    BindingType bindingType,
    Map<KbaChangeSetQualifier,
    KbaChangeSet> kbaChangeSet,
    IPath outputLocation,
    String description) throws FileNotFoundException, IOException {
  String output = getBindingsPrintout(bindingType, kbaChangeSet, description);
  File file = outputLocation.toFile();
  PrintStream stream = null;
  try {
    stream = new PrintStream(new FileOutputStream(file));
    stream.print(output);
  } finally {
    Closeables.closeQuietly(stream);
  }
}
 
開發者ID:alfsch,項目名稱:workspacemechanic,代碼行數:17,代碼來源:KeyBindingsManualFormatter.java

示例14: testMerge

import com.google.common.io.Closeables; //導入依賴的package包/類
@Test
@UseDataProvider("merge")
public void testMerge(InputStream local, InputStream remote, InputStream base, InputStream expected)
    throws IOException {
  MergeClient mergeClient = new ScmPomVersionsMergeClient();
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try {
    mergeClient.merge(local, remote, base, os);
    String result = os.toString();
    Assert.assertEquals(new String(ByteStreams.toByteArray(expected)), result);
  } finally {
    Closeables.closeQuietly(local);
    Closeables.closeQuietly(remote);
    Closeables.closeQuietly(base);
    Closeables.close(os, true);
  }
}
 
開發者ID:shillner,項目名稱:unleash-maven-plugin,代碼行數:18,代碼來源:ScmPomVersionsMergeClientTest.java

示例15: getTranslationKeys

import com.google.common.io.Closeables; //導入依賴的package包/類
/**
 * Loads the keys from the specified translation file into a set.
 * @param file translation file.
 * @return a Set object which holds the loaded keys.
 */
private Set<String> getTranslationKeys(File file) {
    Set<String> keys = new HashSet<String>();
    InputStream inStream = null;
    try {
        inStream = new FileInputStream(file);
        final Properties translations = new Properties();
        translations.load(inStream);
        keys = translations.stringPropertyNames();
    }
    catch (final IOException ex) {
        logIoException(ex, file);
    }
    finally {
        Closeables.closeQuietly(inStream);
    }
    return keys;
}
 
開發者ID:rnveach,項目名稱:checkstyle-backport-jre6,代碼行數:23,代碼來源:TranslationCheck.java


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