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

x33g5p2x  于2022-01-18 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(262)

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

Files.toByteArray介绍

[英]Reads all bytes from a file into a byte array.

java.nio.file.Path equivalent: java.nio.file.Files#readAllBytes.
[中]将文件中的所有字节读入字节数组。
JAVA尼奥。文件路径等价物:java。尼奥。文件文件#readAllBytes。

代码示例

代码示例来源:origin: SonarSource/sonarqube

@Override
protected byte[] readBytes(URI uri) {
 try {
  return Files.toByteArray(new File(uri));
 } catch (IOException e) {
  throw Throwables.propagate(e);
 }
}

代码示例来源:origin: apache/incubator-druid

public static int getVersionFromDir(File inDir) throws IOException
 {
  File versionFile = new File(inDir, "version.bin");
  if (versionFile.exists()) {
   return Ints.fromByteArray(Files.toByteArray(versionFile));
  }

  final File indexFile = new File(inDir, "index.drd");
  int version;
  if (indexFile.exists()) {
   try (InputStream in = new FileInputStream(indexFile)) {
    version = in.read();
   }
   return version;
  }

  throw new IOE("Invalid segment dir [%s]. Can't find either of version.bin or index.drd.", inDir);
 }
}

代码示例来源:origin: dreamhead/moco

@Override
protected byte[] doReadFor(final Optional<? extends Request> request) {
  File file = new File(targetFileName(request));
  if (!file.exists()) {
    throw new IllegalArgumentException(format("%s does not exist", file.getPath()));
  }
  try {
    return toByteArray(file);
  } catch (IOException e) {
    throw new MocoException(e);
  }
}

代码示例来源:origin: qunarcorp/qmq

private void loadSnapshotFile(final File file) {
  try {
    final long version = parseSnapshotVersion(file.getName());
    final byte[] data = Files.toByteArray(file);
    final Snapshot<T> snapshot = new Snapshot<>(version, serde.fromBytes(data));
    snapshots.put(version, snapshot);
    LOG.info("load snapshot file {} success.", file.getAbsolutePath());
  } catch (Exception e) {
    LOG.error("load snapshot file {} failed.", file.getAbsolutePath(), e);
  }
}

代码示例来源:origin: qunarcorp/qmq

public Map<Long, Long> loadScheduleOffsetCheckpoint() {
  File file = new File(config.getScheduleOffsetCheckpointPath(), SCHEDULE_OFFSET_CHECKPOINT);
  if (!file.exists()) {
    return new HashMap<>(0);
  }
  try {
    final byte[] data = Files.toByteArray(file);
    if (data != null && data.length == 0) {
      if (!file.delete()) throw new RuntimeException("remove checkpoint error. filename=" + file);
      return new HashMap<>(0);
    }
    Map<Long, Long> offsets = SERDE.fromBytes(data);
    if (null == offsets || !file.delete()) {
      throw new RuntimeException("Load checkpoint error. filename=" + file);
    }
    return offsets;
  } catch (IOException e) {
    LOGGER.error("Load checkpoint file failed.", e);
  }
  throw new RuntimeException("Load checkpoint failed. filename=" + file);
}

代码示例来源:origin: qunarcorp/qmq

public T loadCheckpoint() {
  final File checkpointFile = checkpointFile();
  final File backupFile = backupFile();
  if (!checkpointFile.exists() && !backupFile.exists()) {
    LOG.warn("Checkpoint file and backup file does not exist, return null for now");
    return null;
  }
  try {
    final byte[] data = Files.toByteArray(checkpointFile);
    if (data != null && data.length == 0) {
      return null;
    }
    return serde.fromBytes(data);
  } catch (IOException e) {
    LOG.error("Load checkpoint file failed. Try load backup checkpoint file instead.", e);
  }
  try {
    return serde.fromBytes(Files.toByteArray(backupFile));
  } catch (IOException e) {
    LOG.error("Load backup checkpoint file failed.", e);
  }
  throw new RuntimeException("Load checkpoint failed. filename=" + filename);
}

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

public void testToByteArray() throws IOException {
 File asciiFile = getTestFile("ascii.txt");
 File i18nFile = getTestFile("i18n.txt");
 assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), Files.toByteArray(asciiFile)));
 assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.toByteArray(i18nFile)));
 assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.asByteSource(i18nFile).read()));
}

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

public void testWriteBytes() throws IOException {
 File temp = createTempFile();
 byte[] data = newPreFilledByteArray(2000);
 Files.write(data, temp);
 assertTrue(Arrays.equals(data, Files.toByteArray(temp)));
 try {
  Files.write(null, temp);
  fail("expected exception");
 } catch (NullPointerException expected) {
 }
}

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

public void testMap_readWrite() throws IOException {
 // Test data
 int size = 1024;
 byte[] expectedBytes = new byte[size];
 byte[] bytes = newPreFilledByteArray(1024);
 // Setup
 File file = createTempFile();
 Files.write(bytes, file);
 Random random = new Random();
 random.nextBytes(expectedBytes);
 // Test
 MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE);
 map.put(expectedBytes);
 // Verify
 byte[] actualBytes = Files.toByteArray(file);
 assertTrue(Arrays.equals(expectedBytes, actualBytes));
}

代码示例来源:origin: dreamhead/moco

@Override
  public void run() throws IOException {
    assertThat(helper.getAsBytes(root()), is(toByteArray(new File("src/test/resources/gbk.response"))));
  }
});

代码示例来源:origin: dreamhead/moco

@Override
  public void run() throws Exception {
    assertThat(helper.getAsBytes(root()), is(toByteArray(new File("src/test/resources/gbk.response"))));
  }
});

代码示例来源:origin: dreamhead/moco

@Override
  public void run() throws Exception {
    assertThat(helper.getAsBytes(remoteUrl("/template")), is(toByteArray(new File("src/test/resources/gbk.response"))));
  }
});

代码示例来源:origin: dreamhead/moco

@Override
  public void run() throws IOException {
    assertThat(helper.postBytes(root(), toByteArray(new File("src/test/resources/gbk.response")), gbk),
        is("bar"));
  }
});

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

public void testReadBytes() throws IOException {
 ByteProcessor<byte[]> processor =
   new ByteProcessor<byte[]>() {
    private final ByteArrayOutputStream out = new ByteArrayOutputStream();
    @Override
    public boolean processBytes(byte[] buffer, int offset, int length) throws IOException {
     if (length >= 0) {
      out.write(buffer, offset, length);
     }
     return true;
    }
    @Override
    public byte[] getResult() {
     return out.toByteArray();
    }
   };
 File asciiFile = getTestFile("ascii.txt");
 byte[] result = Files.readBytes(asciiFile, processor);
 assertEquals(Bytes.asList(Files.toByteArray(asciiFile)), Bytes.asList(result));
}

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

public void testMap_readWrite_creates() throws IOException {
 // Test data
 int size = 1024;
 byte[] expectedBytes = newPreFilledByteArray(1024);
 // Setup
 File file = createTempFile();
 boolean deleted = file.delete();
 assertTrue(deleted);
 assertFalse(file.exists());
 // Test
 MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE, size);
 map.put(expectedBytes);
 // Verify
 assertTrue(file.exists());
 assertTrue(file.isFile());
 assertEquals(size, file.length());
 byte[] actualBytes = Files.toByteArray(file);
 assertTrue(Arrays.equals(expectedBytes, actualBytes));
}

代码示例来源:origin: apache/incubator-druid

long startTime = System.currentTimeMillis();
final int theVersion = Ints.fromByteArray(Files.toByteArray(new File(inDir, "version.bin")));
if (theVersion != V9_VERSION) {
 throw new IAE("Expected version[9], got[%d]", theVersion);

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

byte[]          bytes = Files.toByteArray(source);
S3Utils.simpleUploadFile(s3Client, bytes, configValues.get(CONFIG_BUCKET.getKey()), key);

代码示例来源:origin: org.apache.logging.log4j/log4j-core

public void testNoNulCharacters(final String message, final String expected) throws IOException {
  @SuppressWarnings("resource")
  final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
  final Logger logger = loggerContext.getLogger("com.example");
  logger.error("log:", message);
  loggerContext.stop();
  final File file = new File(FILE_PATH);
  final byte[] contents = Files.toByteArray(file);
  int count0s = 0;
  final StringBuilder sb = new StringBuilder();
  for (int i = 0; i < contents.length; i++) {
    final byte b = contents[i];
    if (b == 0) {
      sb.append(i);
      sb.append(", ");
      count0s++;
    }
  }
  Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
  final List<String> readLines = Files.readLines(file, Charset.defaultCharset());
  final String actual = readLines.get(0);
  // Assert.assertTrue(actual, actual.contains(message));
  Assert.assertEquals(actual, expected, actual);
  Assert.assertEquals(1, readLines.size());
}

代码示例来源:origin: apache/incubator-druid

@Test
public void testLastPushWinsForConcurrentPushes() throws IOException
{
 File replicatedDataSegmentFiles = temporaryFolder.newFolder();
 Files.asByteSink(new File(replicatedDataSegmentFiles, "version.bin")).write(Ints.toByteArray(0x8));
 DataSegment returnSegment1 = localDataSegmentPusher.push(dataSegmentFiles, dataSegment, false);
 DataSegment returnSegment2 = localDataSegmentPusher.push(replicatedDataSegmentFiles, dataSegment2, false);
 Assert.assertEquals(dataSegment.getDimensions(), returnSegment1.getDimensions());
 Assert.assertEquals(dataSegment2.getDimensions(), returnSegment2.getDimensions());
 File unzipDir = new File(config.storageDirectory, "unzip");
 FileUtils.forceMkdir(unzipDir);
 CompressionUtils.unzip(
   new File(config.storageDirectory, "/ds/1970-01-01T00:00:00.000Z_1970-01-01T00:00:00.001Z/v1/0/index.zip"),
   unzipDir
 );
 Assert.assertEquals(0x8, Ints.fromByteArray(Files.toByteArray(new File(unzipDir, "version.bin"))));
}

代码示例来源:origin: opensourceBIM/BIMserver

public static void main(String[] args) {
  try (BimBotClient bimBotCaller = new BimBotClient("http://localhost:8080/services", "a70abb752c5a04f5ccce7ea1b79b85c045c594c3d7fb23d6f28e8e8ad04f2750477ec5706013f2bc07be2b9555fd44df")) {
    BimBotsInput bimBotsInput = new BimBotsInput(SchemaName.IFC_STEP_2X3TC1, Files.toByteArray(new File("C:\\Git\\TestFiles\\TestData\\data\\export3.ifc")));
    BimBotsOutput bimBotsOutput = bimBotCaller.call("3866702", bimBotsInput);
    ObjectNode readValue = new ObjectMapper().readValue(bimBotsOutput.getData(), ObjectNode.class);
    System.out.println(readValue.toString());
  } catch (IOException e) {
    e.printStackTrace();
  } catch (BimBotExecutionException e) {
    e.printStackTrace();
  }
}

相关文章