com.google.common.io.Resources.toByteArray()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(132)

本文整理了Java中com.google.common.io.Resources.toByteArray方法的一些代码示例,展示了Resources.toByteArray的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Resources.toByteArray方法的具体详情如下:
包路径:com.google.common.io.Resources
类名称:Resources
方法名:toByteArray

Resources.toByteArray介绍

[英]Reads all bytes from a URL into a byte array.
[中]将URL中的所有字节读入字节数组。

代码示例

代码示例来源:origin: SpongePowered/SpongeAPI

/**
 * Reads this Asset in it's entirety as a byte array and returns the
 * result.
 *
 * @return Byte array representation of Asset
 * @throws IOException If any file exception is thrown
 */
default byte[] readBytes() throws IOException {
  return Resources.toByteArray(getUrl());
}

代码示例来源:origin: signalapp/BitHub

public static byte[] createFor(String price) throws IOException {
 byte[]        badgeBackground = Resources.toByteArray(Resources.getResource("assets/badge.png"));
 BufferedImage bufferedImage   = ImageIO.read(new ByteArrayInputStream(badgeBackground));
 Graphics2D    graphics        = bufferedImage.createGraphics();
 graphics.setFont(new Font("OpenSans", Font.PLAIN, 34));
 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
              RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
 graphics.drawString(price + " USD", 86, 45);
 graphics.dispose();
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ImageIO.write(bufferedImage, "png", baos);
 return baos.toByteArray();
}

代码示例来源:origin: signalapp/BitHub

public static byte[] createSmallFor(String price) throws IOException {
 byte[]        badgeBackground = Resources.toByteArray(Resources.getResource("assets/badge-small.png"));
 BufferedImage bufferedImage   = ImageIO.read(new ByteArrayInputStream(badgeBackground));
 Graphics2D    graphics        = bufferedImage.createGraphics();
 graphics.setFont(new Font("OpenSans", Font.PLAIN, 9));
 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
              RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
 graphics.drawString(price + " USD", 22, 14);
 graphics.dispose();
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ImageIO.write(bufferedImage, "png", baos);
 return baos.toByteArray();
}

代码示例来源:origin: prestodb/presto

private void copyExecutable(String name, File target)
      throws IOException
  {
    byte[] bytes = toByteArray(Resources.getResource(getClass(), name));
    Path path = target.toPath().resolve(new File(name).getName());
    Files.write(path, bytes);
    if (!path.toFile().setExecutable(true)) {
      throw new IOException("failed to make executable: " + path);
    }
  }
}

代码示例来源:origin: google/guava

public void testToToByteArray() throws IOException {
 byte[] data = Resources.toByteArray(classfile(Resources.class));
 assertEquals(0xCAFEBABE, new DataInputStream(new ByteArrayInputStream(data)).readInt());
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
  @Path("/{route: .*}")
  public Response asset(@PathParam("route") String route) throws IOException {
    // Directory traversal should not be possible but just to make sure..
    if (route.contains("..")) {
      throw new BadRequestException("Not allowed to access parent directory");
    }

    final URL resource = classLoader.getResource("swagger/" + route);
    if (null != resource) {
      try {
        final byte[] resourceBytes = Resources.toByteArray(resource);

        return Response.ok(resourceBytes, mimeTypes.getContentType(route))
            .header("Content-Length", resourceBytes.length)
            .build();
      } catch (IOException e) {
        throw new NotFoundException("Couldn't load " + resource, e);
      }
    } else {
      throw new NotFoundException("Couldn't find " + route);
    }
  }
}

代码示例来源:origin: soabase/exhibitor

entity = Resources.toByteArray(resource);

代码示例来源:origin: Graylog2/graylog2-server

final FileSystem fileSystem = fileSystemCache.getUnchecked(uri);
path = fileSystem.getPath(pluginPrefixFilename(fromPlugin, filename));
fileContents = Resources.toByteArray(resourceUrl);
break;

代码示例来源:origin: line/armeria

@Test
public void testThriftTestJson() throws Exception {
  final Map<String, String> docStrings = extractor.getDocStringsFromFiles(
      ImmutableMap.of(
          "META-INF/armeria/thrift/ThriftTest.json",
          Resources.toByteArray(Resources.getResource(
              "META-INF/armeria/thrift/ThriftTest.json"))));
  assertThat(docStrings.get("thrift.test.Numberz")).isEqualTo("Docstring!");
  assertThat(docStrings.get("thrift.test.ThriftTest/testVoid")).isEqualTo(
      "Prints \"testVoid()\" and returns nothing.");
}

代码示例来源:origin: line/armeria

@Test
public void testCassandraJson() throws Exception {
  final Map<String, String> docStrings = extractor.getDocStringsFromFiles(
      ImmutableMap.of(
          "META-INF/armeria/thrift/ThriftTest.json",
          Resources.toByteArray(Resources.getResource(
              "META-INF/armeria/thrift/cassandra.json"))));
  assertThat(docStrings.get("com.linecorp.armeria.service.test.thrift.cassandra.Compression"))
       .isEqualTo("CQL query compression");
  assertThat(
      docStrings.get("com.linecorp.armeria.service.test.thrift.cassandra.CqlResultType")).isNull();
}

代码示例来源:origin: line/armeria

private Map<String, String> getAllDocStrings0(ClassLoader classLoader) {
  final Configuration configuration = new ConfigurationBuilder()
      .filterInputsBy(new FilterBuilder().includePackage(path))
      .setUrls(ClasspathHelper.forPackage(path, classLoader))
      .addClassLoader(classLoader)
      .setScanners(new ResourcesScanner());
  if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
    return Collections.emptyMap();
  }
  final Map<String, byte[]> files = new Reflections(configuration)
      .getResources(this::acceptFile).stream()
      .map(f -> {
        try {
          URL url = classLoader.getResource(f);
          if (url == null) {
            throw new IllegalStateException("not found: " + f);
          }
          return new SimpleImmutableEntry<>(f, Resources.toByteArray(url));
        } catch (IOException e) {
          throw new UncheckedIOException(e);
        }
      })
      .collect(toImmutableMap(Entry::getKey, Entry::getValue));
  return getDocStringsFromFiles(files);
}

代码示例来源:origin: apache/hive

if (sparkDefaultsUrl != null) {
 LOG.info("Loading spark defaults configs from: " + sparkDefaultsUrl);
 allProps.load(new ByteArrayInputStream(Resources.toByteArray(sparkDefaultsUrl)));

代码示例来源:origin: google/error-prone

ApiDiffProto.Diff.Builder diffBuilder = ApiDiffProto.Diff.newBuilder();
byte[] diffData =
  Resources.toByteArray(Resources.getResource(Java7ApiChecker.class, "7to8diff.binarypb"));
diffBuilder
  .mergeFrom(diffData)

代码示例来源:origin: glowroot/glowroot

static byte[] getBytes(String className, @Nullable File pluginJar) throws IOException {
  String resourceName = "/" + className + ".class";
  URL url = PluginDetailBuilder.class.getResource(resourceName);
  if (url != null) {
    return Resources.toByteArray(url);
  }
  if (pluginJar != null) {
    url = new URL("jar:" + pluginJar.toURI() + "!" + resourceName);
    return Resources.toByteArray(url);
  }
  throw new IOException("Class not found: " + className);
}

代码示例来源:origin: glowroot/glowroot

private static byte[] getBytesFromJarFile(String name, File jarFile) throws IOException {
  String path = jarFile.getPath();
  URI uri;
  try {
    uri = new URI("jar", "file:" + path + "!/" + name, "");
  } catch (URISyntaxException e) {
    // this is a programmatic error
    throw new RuntimeException(e);
  }
  return Resources.toByteArray(uri.toURL());
}

代码示例来源:origin: glowroot/glowroot

private static byte[] getBytesFromDirectoryInsideJarFile(String name, File jarFile,
    String directoryInsideJarFile) throws IOException {
  String path = jarFile.getPath();
  URI uri;
  try {
    uri = new URI("jar", "file:" + path + "!/" + directoryInsideJarFile + name, "");
  } catch (URISyntaxException e) {
    // this is a programmatic error
    throw new RuntimeException(e);
  }
  return Resources.toByteArray(uri.toURL());
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void streamingRecognize() throws Exception {
 byte[] audioBytes =
   Resources.toByteArray(new URL("https://storage.googleapis.com/gapic-toolkit/hello.flac"));
 StreamingRecognitionConfig streamingConfig =
   StreamingRecognitionConfig.newBuilder().setConfig(config()).build();
 ResponseApiStreamingObserver<StreamingRecognizeResponse> responseObserver =
   new ResponseApiStreamingObserver<>();
 ApiStreamObserver<StreamingRecognizeRequest> requestObserver =
   speechClient.streamingRecognizeCallable().bidiStreamingCall(responseObserver);
 // The first request must **only** contain the audio configuration:
 requestObserver.onNext(
   StreamingRecognizeRequest.newBuilder().setStreamingConfig(streamingConfig).build());
 // Subsequent requests must **only** contain the audio data.
 requestObserver.onNext(
   StreamingRecognizeRequest.newBuilder()
     .setAudioContent(ByteString.copyFrom(audioBytes))
     .build());
 // Mark transmission as completed after sending the data.
 requestObserver.onCompleted();
 List<StreamingRecognizeResponse> responses = responseObserver.future().get();
 Truth.assertThat(responses.size()).isGreaterThan(0);
 Truth.assertThat(responses.get(0).getResultsCount()).isGreaterThan(0);
 Truth.assertThat(responses.get(0).getResults(0).getAlternativesCount()).isGreaterThan(0);
 String text = responses.get(0).getResults(0).getAlternatives(0).getTranscript();
 Truth.assertThat(text).isEqualTo("hello");
}

代码示例来源:origin: glowroot/glowroot

bytes = Resources.toByteArray(url);
} catch (IOException e) {
  throw new ClassNotFoundException("Error loading class", e);

代码示例来源:origin: glowroot/glowroot

private static byte[] getBytes(Location location, String className) throws IOException {
  String name = className.replace('.', '/') + ".class";
  File dir = location.directory();
  File jarFile = location.jarFile();
  if (dir != null) {
    URI uri = new File(dir, name).toURI();
    return Resources.toByteArray(uri.toURL());
  } else if (jarFile != null) {
    String jarFileInsideJarFile = location.jarFileInsideJarFile();
    String directoryInsideJarFile = location.directoryInsideJarFile();
    if (jarFileInsideJarFile == null && directoryInsideJarFile == null) {
      return getBytesFromJarFile(name, jarFile);
    } else if (jarFileInsideJarFile != null) {
      return getBytesFromJarFileInsideJarFile(name, jarFile, jarFileInsideJarFile);
    } else {
      // directoryInsideJarFile is not null based on above conditionals
      checkNotNull(directoryInsideJarFile);
      return getBytesFromDirectoryInsideJarFile(name, jarFile, directoryInsideJarFile);
    }
  } else {
    throw new AssertionError("Both Location directory() and jarFile() are null");
  }
}

代码示例来源:origin: glowroot/glowroot

byte[] bytes = Resources.toByteArray(url);
List<Advice> advisors =
    mergeInstrumentationAnnotations(this.advisors.get(), bytes, loader, className);

相关文章