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


Java ByteStreams类代码示例

本文整理汇总了Java中com.google.common.io.ByteStreams的典型用法代码示例。如果您正苦于以下问题:Java ByteStreams类的具体用法?Java ByteStreams怎么用?Java ByteStreams使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: expandZippedApplication

import com.google.common.io.ByteStreams; //导入依赖的package包/类
private void expandZippedApplication(InputStream stream, ApplicationDescription desc)
        throws IOException {
    ZipInputStream zis = new ZipInputStream(stream);
    ZipEntry entry;
    File appDir = new File(appsDir, desc.name());
    while ((entry = zis.getNextEntry()) != null) {
        if (!entry.isDirectory()) {
            byte[] data = ByteStreams.toByteArray(zis);
            zis.closeEntry();
            File file = new File(appDir, entry.getName());
            createParentDirs(file);
            write(data, file);
        }
    }
    zis.close();
}
 
开发者ID:shlee89,项目名称:athena,代码行数:17,代码来源:ApplicationArchive.java

示例2: open

import com.google.common.io.ByteStreams; //导入依赖的package包/类
/**
 * @see org.alfasoftware.morf.xml.XmlStreamProvider#open()
 */
@Override
public void open() {
  if (zipOutput != null) {
    throw new IllegalStateException("Archive data set instance for [" + file + "] already open");
  }

  try {
    zipOutput = new AdaptedZipOutputStream(new FileOutputStream(file));

    // Put the read me entry in
    ZipEntry entry = new ZipEntry("_ReadMe.txt");
    zipOutput.putNextEntry(entry);
    ByteStreams.copy(new ByteArrayInputStream(READ_ME.getBytes("UTF-8")), zipOutput);
  } catch (Exception e) {
    throw new RuntimeException("Error opening zip archive [" + file + "]", e);
  }
}
 
开发者ID:alfasoftware,项目名称:morf,代码行数:21,代码来源:ArchiveDataSetWriter.java

示例3: onPluginMessageReceived

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
    if (!channel.equals("BungeeCord")) {
        return;
    }
    final ByteArrayDataInput in = ByteStreams.newDataInput(message);
    final String type = in.readUTF();
    if (type.equals("ServerIP")) {
        final String serverName = in.readUTF();
        final String ip = in.readUTF();
        final short port = in.readShort();
        this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> {
            final String data = BungeeCordProvider.this.receiveResultFromServer(serverName, ip, port);
            BungeeCordProvider.this.parseData(serverName, data);
        });
    }
}
 
开发者ID:Shynixn,项目名称:BlockBall,代码行数:18,代码来源:BungeeCordProvider.java

示例4: handleChannel

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@EventHandler
public void handleChannel(PluginMessageEvent pluginMessageEvent)
{
    if(!(pluginMessageEvent.getReceiver() instanceof ProxiedPlayer)) return;
    if(pluginMessageEvent.getTag().equalsIgnoreCase("CloudNet"))
    {
        ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(pluginMessageEvent.getData());
        switch (byteArrayDataInput.readUTF().toLowerCase())
        {
            case "connect":
                List<String> servers = CloudProxy.getInstance().getServers(byteArrayDataInput.readUTF()); if(servers.size() == 0) return;
                ((ProxiedPlayer)pluginMessageEvent.getReceiver()).connect(ProxyServer.getInstance().getServerInfo(servers.get(NetworkUtils.RANDOM.nextInt(servers.size()))));
                break;
            case "fallback":
                ((ProxiedPlayer)pluginMessageEvent.getReceiver()).connect(ProxyServer.getInstance()
                        .getServerInfo(CloudProxy.getInstance()
                        .fallback(((ProxiedPlayer)pluginMessageEvent.getReceiver()))));
                break;
            case "command":
                ProxyServer.getInstance().getPluginManager().dispatchCommand(((ProxiedPlayer)pluginMessageEvent.getReceiver()), byteArrayDataInput.readUTF());
                break;
        }
    }
}
 
开发者ID:Dytanic,项目名称:CloudNet,代码行数:25,代码来源:ProxiedListener.java

示例5: publicize

import com.google.common.io.ByteStreams; //导入依赖的package包/类
private static void publicize(Path inPath, Path outPath) throws IOException {
	try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) {
		try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) {
			JarEntry entry;
			while ((entry = in.getNextJarEntry()) != null) {
				if (entry.isDirectory()) {
					continue;
				}

				String name = entry.getName();
				out.putNextEntry(new JarEntry(name));

				if (name.endsWith(".class")) {
					ClassWriter writer = new ClassWriter(0);

					ClassReader reader = new ClassReader(in);
					reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0);

					out.write(writer.toByteArray());
				} else {
					ByteStreams.copy(in, out);
				}
			}
		}
	}
}
 
开发者ID:jonathanedgecombe,项目名称:anvil,代码行数:27,代码来源:Publicizer.java

示例6: fromInputStream

import com.google.common.io.ByteStreams; //导入依赖的package包/类
public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is)
        throws IOException {
    if (!is.markSupported()) {
        throw new IllegalArgumentException("InputStream must support mark");
    }
    is.mark(44);
    byte[] partialHeader = new byte[44];
    try {
        ByteStreams.readFully(is, partialHeader);
    } catch (EOFException ex) {
        throw new NotADexFile("File is too short");
    } finally {
        is.reset();
    }

    verifyMagicAndByteOrder(partialHeader, 0);

    byte[] buf = ByteStreams.toByteArray(is);
    return new DexBackedDexFile(opcodes, buf, 0, false);
}
 
开发者ID:CvvT,项目名称:andbg,代码行数:21,代码来源:DexBackedDexFile.java

示例7: getFileAsBinData

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private BinData getFileAsBinData(FileHandle file, String filename)
{
	try( InputStream in = fileSystemService.read(file, filename) )
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ByteStreams.copy(in, baos);

		BinData data = new BinData();
		data.getContent().add(new PCData(new Base64().encode(baos.toByteArray())));
		return data;
	}
	catch( IOException io )
	{
		throw Throwables.propagate(io);
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:18,代码来源:AbstractMetsAttachmentImportExporter.java

示例8: ZipMemDataSource

import com.google.common.io.ByteStreams; //导入依赖的package包/类
ZipMemDataSource(String fileName, InputStream content) {
    super(DataSourceUtil.getBaseName(fileName));

    Objects.requireNonNull(content);
    try (ZipInputStream zipStream = new ZipInputStream(content)) {
        ZipEntry entry = zipStream.getNextEntry();
        while (entry != null) {
            String entryName = entry.getName();
            try (ByteArrayOutputStream bao = new ByteArrayOutputStream()) {
                ByteStreams.copy(zipStream, bao);
                putData(entryName, bao.toByteArray());
            }
            entry = zipStream.getNextEntry();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
开发者ID:powsybl,项目名称:powsybl-core,代码行数:19,代码来源:ZipMemDataSource.java

示例9: testDataSource

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@Override
protected ReadOnlyMemDataSource testDataSource(String extension) throws IOException {
    ReadOnlyMemDataSource dataSource = super.testDataSource(extension);

    assertTrue(dataSource.exists("extra_data.xiidm"));
    assertArrayEquals(getExtraUncompressedData(), ByteStreams.toByteArray(dataSource.newInputStream("extra_data.xiidm")));

    try {
        assertFalse(dataSource.exists("_data", "xiidm")); // baseName = data, data_data.xiidm does not exist
        assertArrayEquals(getExtraUncompressedData(), ByteStreams.toByteArray(dataSource.newInputStream("_data", "xiidm")));
        fail();
    } catch (IOException ignored) {
    }

    return dataSource;
}
 
开发者ID:powsybl,项目名称:powsybl-core,代码行数:17,代码来源:ZipMemDataSourceTest.java

示例10: exporter

import com.google.common.io.ByteStreams; //导入依赖的package包/类
private FileWorker exporter(final Control control)
{
	return new AbstractFileWorker<Object>(CurrentLocale.get("com.tle.admin.controls.exported"), //$NON-NLS-1$
		CurrentLocale.get("com.tle.admin.controls.error.exporting")) //$NON-NLS-1$
	{
		@Override
		public Object construct() throws Exception
		{
			final Driver driver = Driver.instance();
			final PluginService pluginService = driver.getPluginService();

			final ExportedControl ctl = getExportedControl(control, pluginService, driver.getVersion().getFull());

			byte[] zipData = getCollectionService(driver).exportControl(new XStream().toXML(ctl));

			ByteArrayInputStream stream = new ByteArrayInputStream(zipData);
			try( OutputStream out = new FileOutputStream(file) )
			{
				ByteStreams.copy(stream, out);
			}
			return null;
		}
	};
}
 
开发者ID:equella,项目名称:Equella,代码行数:25,代码来源:WizardTree.java

示例11: unzip

import com.google.common.io.ByteStreams; //导入依赖的package包/类
public static List<File> unzip(String zipFile, File outDirectory, Predicate<ZipEntry> filter)
    throws IOException {
  final Path outDirectoryPath = outDirectory.toPath();
  final List<File> outFiles = new ArrayList<>();
    iter(zipFile, (entry, input) -> {
      String name = entry.getName();
      if (!entry.isDirectory() && filter.test(entry)) {
        if (name.contains("..")) {
          // Protect against malicious archives.
          throw new CompilationError("Invalid entry name \"" + name + "\"");
        }
        Path outPath = outDirectoryPath.resolve(name);
        File outFile = outPath.toFile();
        outFile.getParentFile().mkdirs();
        FileOutputStream output = new FileOutputStream(outFile);
        ByteStreams.copy(input, output);
        outFiles.add(outFile);
      }
    });
  return outFiles;
}
 
开发者ID:inferjay,项目名称:r8,代码行数:22,代码来源:ZipUtils.java

示例12: buildAndTreeShakeFromDeployJar

import com.google.common.io.ByteStreams; //导入依赖的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);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:23,代码来源:YouTubeTreeShakeJarVerificationTest.java

示例13: encodeString

import com.google.common.io.ByteStreams; //导入依赖的package包/类
/**
 * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
 * Strings are prefixed by 2 values. The first is the number of characters in the string.
 * The second is the encoding length (number of bytes in the string).
 *
 * <p>Here's an example UTF-8-encoded string of ab©:
 * <pre>03 04 61 62 C2 A9 00</pre>
 *
 * @param str The string to be encoded.
 * @param type The encoding type that the {@link ResourceString} should be encoded in.
 * @return The encoded string.
 */
public static byte[] encodeString(String str, Type type) {
  byte[] bytes = str.getBytes(type.charset());
  // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
  ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
  encodeLength(output, str.length(), type);
  if (type == Type.UTF8) {  // Only UTF-8 strings have the encoding length.
    encodeLength(output, bytes.length, type);
  }
  output.write(bytes);
  // NULL-terminate the string
  if (type == Type.UTF8) {
    output.write(0);
  } else {
    output.writeShort(0);
  }
  return output.toByteArray();
}
 
开发者ID:madisp,项目名称:android-chunk-utils,代码行数:30,代码来源:ResourceString.java

示例14: testHandleResponse

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@Test
public void testHandleResponse() throws IOException, UnexpectedBlobDigestException {
  Blob testBlob = Blobs.from("some BLOB content");
  DescriptorDigest testBlobDigest = testBlob.writeTo(ByteStreams.nullOutputStream()).getDigest();

  Response mockResponse = Mockito.mock(Response.class);
  Mockito.when(mockResponse.getBody()).thenReturn(testBlob);

  BlobPuller blobPuller =
      new BlobPuller(fakeRegistryEndpointProperties, testBlobDigest, temporaryPath);
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  BlobDescriptor blobDescriptor =
      blobPuller.handleResponse(mockResponse).writeTo(byteArrayOutputStream);
  Assert.assertEquals(
      "some BLOB content",
      new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8));
  Assert.assertEquals(testBlobDigest, blobDescriptor.getDigest());
}
 
开发者ID:GoogleCloudPlatform,项目名称:minikube-build-tools-for-java,代码行数:19,代码来源:BlobPullerTest.java

示例15: getBinResource

import com.google.common.io.ByteStreams; //导入依赖的package包/类
@Path("{resource}")
@GET
@Produces("image/png")
public Response getBinResource(@PathParam("resource") String resource)
        throws IOException {

    String path = ROOT + resource;
    InputStream is = getClass().getClassLoader().getResourceAsStream(path);

    if (is == null) {
        log.warn("Didn't find resource {}", path);
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    byte[] bytes = ByteStreams.toByteArray(is);
    log.info("Processing resource {} ({} bytes)", path, bytes.length);
    return Response.ok(decodeAndMark(bytes)).build();
}
 
开发者ID:shlee89,项目名称:athena,代码行数:19,代码来源:FooResource.java


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