Java Code Examples for com.google.common.io.Files.toByteArray()

The following are Jave code examples for showing how to use toByteArray() of the com.google.common.io.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: UpgradeUtilities.java   View Source Code Vote up 9 votes
/**
 * Corrupt the specified file.  Some random bytes within the file
 * will be changed to some random values.
 *
 * @throws IllegalArgumentException if the given file is not a file
 * @throws IOException if an IOException occurs while reading or writing the file
 */
public static void corruptFile(File file,
    byte[] stringToCorrupt,
    byte[] replacement) throws IOException {
  Preconditions.checkArgument(replacement.length == stringToCorrupt.length);
  if (!file.isFile()) {
    throw new IllegalArgumentException(
        "Given argument is not a file:" + file);
  }
  byte[] data = Files.toByteArray(file);
  int index = Bytes.indexOf(data, stringToCorrupt);
  if (index == -1) {
    throw new IOException(
        "File " + file + " does not contain string " +
        new String(stringToCorrupt));
  }

  for (int i = 0; i < stringToCorrupt.length; i++) {
    data[index + i] = replacement[i];
  }
  Files.write(data, file);
}
 
Example 2
Project: Reer   File: ClassChangeProcessor.java   View Source Code Vote up 6 votes
public void processChange(final InputFileDetails input, final RecompilationSpec spec) {
    // Do not process
    if (input.isRemoved()) {
        return;
    }

    final ClassReader classReader;
    try {
        classReader = new Java9ClassReader(Files.toByteArray(input.getFile()));
    } catch (IOException e) {
        throw new IllegalArgumentException(String.format("Unable to read class file: '%s'", input.getFile()));
    }

    String className = classReader.getClassName().replaceAll("/", ".");
    DependentsSet actualDependents = previousCompilation.getDependents(className);
    if (actualDependents.isDependencyToAll()) {
        spec.setFullRebuildCause(actualDependents.getDescription(), input.getFile());
    } else {
        spec.getClassNames().addAll(actualDependents.getDependentClasses());
    }
}
 
Example 3
Project: Reer   File: FileCacheBackedScriptClassCompiler.java   View Source Code Vote up 6 votes
private void remapClasses(File scriptCacheDir, File relocalizedDir, RemappingScriptSource source) {
    ScriptSource origin = source.getSource();
    String className = origin.getClassName();
    if (!relocalizedDir.exists()) {
        relocalizedDir.mkdir();
    }
    File[] files = scriptCacheDir.listFiles();
    if (files != null) {
        for (File file : files) {
            String renamed = file.getName();
            if (renamed.startsWith(RemappingScriptSource.MAPPED_SCRIPT)) {
                renamed = className + renamed.substring(RemappingScriptSource.MAPPED_SCRIPT.length());
            }
            ClassWriter cv = new ClassWriter(0);
            BuildScriptRemapper remapper = new BuildScriptRemapper(cv, origin);
            try {
                ClassReader cr = new ClassReader(Files.toByteArray(file));
                cr.accept(remapper, 0);
                Files.write(cv.toByteArray(), new File(relocalizedDir, renamed));
            } catch (IOException ex) {
                throw UncheckedException.throwAsUncheckedException(ex);
            }
        }
    }
}
 
Example 4
Project: appinventor-extensions   File: ProjectBuilder.java   View Source Code Vote up 6 votes
private static Set<String> getComponentTypes(List<String> files, File assetsDir)
    throws IOException, JSONException {
  Map<String, String> nameTypeMap = createNameTypeMap(assetsDir);

  Set<String> componentTypes = Sets.newHashSet();
  for (String f : files) {
    if (f.endsWith(".scm")) {
      File scmFile = new File(f);
      String scmContent = new String(Files.toByteArray(scmFile),
          PathUtil.DEFAULT_CHARSET);
      for (String compName : getTypesFromScm(scmContent)) {
        componentTypes.add(nameTypeMap.get(compName));
      }
    }
  }
  return componentTypes;
}
 
Example 5
Project: Reer   File: MapFileTree.java   View Source Code Vote up 5 votes
private boolean hasContent(byte[] generatedContent, File file) {
    if (generatedContent.length != file.length()) {
        return false;
    }

    byte[] existingContent;
    try {
        existingContent = Files.toByteArray(this.file);
    } catch (IOException e) {
        // Assume changed if reading old file fails
        return false;
    }

    return Arrays.equals(generatedContent, existingContent);
}
 
Example 6
Project: shibboleth-idp-oidc-extension   File: OIDCClientRegistrationRequestDecoderTest.java   View Source Code Vote up 5 votes
@Test
public void testRequestDecoding() throws MessageDecodingException, IOException {
    byte[] bytes = Files.toByteArray(new File("src/test/resources/org/geant/idpextension/oidc/decoding/impl/client-registration-request.json"));
    httpRequest.setContent(bytes);
    httpRequest.setContentType("application/json");
    decoder.decode();
    final MessageContext<OIDCClientRegistrationRequest> messageContext = decoder
            .getMessageContext();
    final OIDCClientRegistrationRequest message = messageContext.getMessage();
    // We are not testing nimbus itself here, i.e. we are happy to decode
    // one parameter successfully
    Assert.assertEquals(message.getClientMetadata().getName(), "My Example");
}
 
Example 7
Project: multidexlib2   File: RawDexIO.java   View Source Code Vote up 5 votes
public static DexBackedDexFile readRawDexFile(File file, Opcodes opcodes) throws IOException {
	/*
	try (InputStream inputStream = new FileInputStream(file)) {
		return readRawDexFile(inputStream, file.length(), opcodes);
	}
	*/
	byte[] buf = Files.toByteArray(file);
	return readRawDexFile(buf, 0, opcodes);
}
 
Example 8
Project: beaker-notebook-archive   File: MIMEContainer.java   View Source Code Vote up 5 votes
protected static byte[] getBytes(Object data) throws IOException {
  byte[] bytes;
  if (isValidURL(data.toString())) {
    bytes = ByteStreams.toByteArray((new URL(data.toString()).openStream()));
  } else if (exists(data.toString())) {
    File imgFile = new File(data.toString());
    bytes = Files.toByteArray(imgFile);
  } else {
    throw new FileNotFoundException(data.toString() + " doesn't exist. ");
  }
  return bytes;
}
 
Example 9
Project: beaker-notebook-archive   File: SimpleClassLoader.java   View Source Code Vote up 5 votes
protected Class<?> findClassInFileSystem(String qualifiedClassName) {
    for (File classDirectory : classDirectories) {
        File classFile = new File(classDirectory, qualifiedClassName.replace('.', '/') + ".class");
        if (classFile.exists()) {
            try {
                byte[] byteCode = Files.toByteArray(classFile);
                return defineClass(qualifiedClassName, byteCode, 0, byteCode.length);
            } catch (IOException e) {
                throw new IllegalStateException("Failed to read class file " + classFile, e);
            }
        }
    }
    return null;
}
 
Example 10
Project: flume-release-1.7.0   File: TestMorphlineSolrSink.java   View Source Code Vote up 5 votes
private void testDocumentTypesInternal(String... files) throws Exception {
    int numDocs = 0;
    long startTime = System.currentTimeMillis();
    
    assertEquals(numDocs, queryResultSetSize("*:*"));      
//  assertQ(req("*:*"), "//*[@numFound='0']");
    for (int i = 0; i < 1; i++) {      
      for (String file : files) {
        File f = new File(file);
        byte[] body = Files.toByteArray(f);
        Event event = EventBuilder.withBody(body);
        event.getHeaders().put(Fields.ATTACHMENT_NAME, f.getName());
        load(event);
        Integer count = expectedRecords.get(file);
        if (count != null) {
          numDocs += count;
        } else {
          numDocs++;
        }
        assertEquals(numDocs, queryResultSetSize("*:*"));
      }
      LOGGER.trace("iter: {}", i);
    }
    LOGGER.trace("all done with put at {}", System.currentTimeMillis() - startTime);
    assertEquals(numDocs, queryResultSetSize("*:*"));
    LOGGER.trace("sink: ", sink);
  }
 
Example 11
Project: hadoop   File: BestEffortLongFile.java   View Source Code Vote up 5 votes
private void lazyOpen() throws IOException {
  if (ch != null) {
    return;
  }

  // Load current value.
  byte[] data = null;
  try {
    data = Files.toByteArray(file);
  } catch (FileNotFoundException fnfe) {
    // Expected - this will use default value.
  }

  if (data != null && data.length != 0) {
    if (data.length != Longs.BYTES) {
      throw new IOException("File " + file + " had invalid length: " +
          data.length);
    }
    value = Longs.fromByteArray(data);
  } else {
    value = defaultVal;
  }
  
  // Now open file for future writes.
  RandomAccessFile raf = new RandomAccessFile(file, "rw");
  try {
    ch = raf.getChannel();
  } finally {
    if (ch == null) {
      IOUtils.closeStream(raf);
    }
  }
}
 
Example 12
Project: appinventor-extensions   File: TempFilesTest.java   View Source Code Vote up 5 votes
public void testCreateAndDeleteTempFile() throws Exception {
  byte[] data = "Hello world.".getBytes(Charsets.UTF_8);
  File tmpFile = TempFiles.createTempFile(data);
  assertTrue(tmpFile.exists());
  byte[] read = Files.toByteArray(tmpFile);
  assertTrue(Arrays.equals(data, read));

  TempFiles.deleteTempFile(tmpFile);
  assertFalse(tmpFile.exists());
}
 
Example 13
Project: test.rockitizer   File: FileUtils.java   View Source Code Vote up 5 votes
public static byte[] getContents(File file)  {
	byte[] content;
	try {
		
		content =  Files.toByteArray(file);
	} catch (IOException e) {
		LOGGER.error(e);
		throw new GenericException(e);
	} 
	return content;
	
}
 
Example 14
Project: javaide   File: XmlUtils.java   View Source Code Vote up 4 votes
/**
 * Returns a character reader for the given file, which must be a UTF encoded file.
 * <p>
 * The reader does not need to be closed by the caller (because the file is read in
 * full in one shot and the resulting array is then wrapped in a byte array input stream,
 * which does not need to be closed.)
 */
public static Reader getUtfReader(@NonNull File file) throws IOException {
    byte[] bytes = Files.toByteArray(file);
    int length = bytes.length;
    if (length == 0) {
        return new StringReader("");
    }

    switch (bytes[0]) {
        case (byte)0xEF: {
            if (length >= 3
                    && bytes[1] == (byte)0xBB
                    && bytes[2] == (byte)0xBF) {
                // UTF-8 BOM: EF BB BF: Skip it
                return new InputStreamReader(new ByteArrayInputStream(bytes, 3, length - 3),
                        UTF_8);
            }
            break;
        }
        case (byte)0xFE: {
            if (length >= 2
                    && bytes[1] == (byte)0xFF) {
                // UTF-16 Big Endian BOM: FE FF
                return new InputStreamReader(new ByteArrayInputStream(bytes, 2, length - 2),
                        UTF_16BE);
            }
            break;
        }
        case (byte)0xFF: {
            if (length >= 2
                    && bytes[1] == (byte)0xFE) {
                if (length >= 4
                        && bytes[2] == (byte)0x00
                        && bytes[3] == (byte)0x00) {
                    // UTF-32 Little Endian BOM: FF FE 00 00
                    return new InputStreamReader(new ByteArrayInputStream(bytes, 4,
                            length - 4), "UTF-32LE");
                }

                // UTF-16 Little Endian BOM: FF FE
                return new InputStreamReader(new ByteArrayInputStream(bytes, 2, length - 2),
                        UTF_16LE);
            }
            break;
        }
        case (byte)0x00: {
            if (length >= 4
                    && bytes[0] == (byte)0x00
                    && bytes[1] == (byte)0x00
                    && bytes[2] == (byte)0xFE
                    && bytes[3] == (byte)0xFF) {
                // UTF-32 Big Endian BOM: 00 00 FE FF
                return new InputStreamReader(new ByteArrayInputStream(bytes, 4, length - 4),
                        "UTF-32BE");
            }
            break;
        }
    }

    // No byte order mark: Assume UTF-8 (where the BOM is optional).
    return new InputStreamReader(new ByteArrayInputStream(bytes), UTF_8);
}
 
Example 15
Project: CustomWorldGen   File: GenDiffSet.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws IOException
    {
        String sourceJar = args[0]; //Clean Vanilla jar minecraft.jar or minecraft_server.jar
        String targetDir = args[1]; //Directory containing obfed output classes, typically mcp/reobf/minecraft
        String deobfData = args[2]; //Path to FML's deobfusication_data.lzma
        String outputDir = args[3]; //Path to place generated .binpatch
        String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch

        LogManager.getLogger("GENDIFF").log(Level.INFO, String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
        Delta delta = new Delta();
        FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
        remapper.setupLoadOnly(deobfData, false);
        JarFile sourceZip = new JarFile(sourceJar);
        boolean kill = killTarget.equalsIgnoreCase("true");

        File f = new File(outputDir);
        f.mkdirs();

        for (String name : remapper.getObfedClasses())
        {
//            Logger.getLogger("GENDIFF").info(String.format("Evaluating path for data :%s",name));
            String fileName = name;
            String jarName = name;
            if (RESERVED_NAMES.contains(name.toUpperCase(Locale.ENGLISH)))
            {
                fileName = "_"+name;
            }
            File targetFile = new File(targetDir, fileName.replace('/', File.separatorChar) + ".class");
            jarName = jarName+".class";
            if (targetFile.exists())
            {
                String sourceClassName = name.replace('/', '.');
                String targetClassName = remapper.map(name).replace('/', '.');
                JarEntry entry = sourceZip.getJarEntry(jarName);
                byte[] vanillaBytes = toByteArray(sourceZip, entry);
                byte[] patchedBytes = Files.toByteArray(targetFile);

                byte[] diff = delta.compute(vanillaBytes, patchedBytes);


                ByteArrayDataOutput diffOut = ByteStreams.newDataOutput(diff.length + 50);
                // Original name
                diffOut.writeUTF(name);
                // Source name
                diffOut.writeUTF(sourceClassName);
                // Target name
                diffOut.writeUTF(targetClassName);
                // exists at original
                diffOut.writeBoolean(entry != null);
                if (entry != null)
                {
                    diffOut.writeInt(Hashing.adler32().hashBytes(vanillaBytes).asInt());
                }
                // length of patch
                diffOut.writeInt(diff.length);
                // patch
                diffOut.write(diff);

                File target = new File(outputDir, targetClassName+".binpatch");
                target.getParentFile().mkdirs();
                Files.write(diffOut.toByteArray(), target);
                Logger.getLogger("GENDIFF").info(String.format("Wrote patch for %s (%s) at %s",name, targetClassName, target.getAbsolutePath()));
                if (kill)
                {
                    targetFile.delete();
                    Logger.getLogger("GENDIFF").info(String.format("  Deleted target: %s", targetFile.toString()));
                }
            }
        }
        sourceZip.close();
    }
 
Example 16
Project: util   File: FileUtil.java   View Source Code Vote up 4 votes
/**
 * 读取文件到byte[].
 */
public static byte[] toByteArray(final File file) throws IOException {
	return Files.toByteArray(file);
}