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


Java Files.toByteArray方法代码示例

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


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

示例1: corruptFile

import com.google.common.io.Files; //导入方法依赖的package包/类
/**
 * 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);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:29,代码来源:UpgradeUtilities.java

示例2: processChange

import com.google.common.io.Files; //导入方法依赖的package包/类
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());
    }
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:22,代码来源:ClassChangeProcessor.java

示例3: remapClasses

import com.google.common.io.Files; //导入方法依赖的package包/类
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);
            }
        }
    }
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:26,代码来源:FileCacheBackedScriptClassCompiler.java

示例4: getComponentTypes

import com.google.common.io.Files; //导入方法依赖的package包/类
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;
}
 
开发者ID:mit-cml,项目名称:appinventor-extensions,代码行数:18,代码来源:ProjectBuilder.java

示例5: hasContent

import com.google.common.io.Files; //导入方法依赖的package包/类
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);
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:16,代码来源:MapFileTree.java

示例6: testRequestDecoding

import com.google.common.io.Files; //导入方法依赖的package包/类
@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");
}
 
开发者ID:CSCfi,项目名称:shibboleth-idp-oidc-extension,代码行数:14,代码来源:OIDCClientRegistrationRequestDecoderTest.java

示例7: readRawDexFile

import com.google.common.io.Files; //导入方法依赖的package包/类
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);
}
 
开发者ID:DexPatcher,项目名称:multidexlib2,代码行数:10,代码来源:RawDexIO.java

示例8: getBytes

import com.google.common.io.Files; //导入方法依赖的package包/类
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;
}
 
开发者ID:twosigma,项目名称:beaker-notebook-archive,代码行数:13,代码来源:MIMEContainer.java

示例9: findClassInFileSystem

import com.google.common.io.Files; //导入方法依赖的package包/类
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;
}
 
开发者ID:twosigma,项目名称:beaker-notebook-archive,代码行数:15,代码来源:SimpleClassLoader.java

示例10: testDocumentTypesInternal

import com.google.common.io.Files; //导入方法依赖的package包/类
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);
  }
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:28,代码来源:TestMorphlineSolrSink.java

示例11: lazyOpen

import com.google.common.io.Files; //导入方法依赖的package包/类
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);
    }
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:BestEffortLongFile.java

示例12: testCreateAndDeleteTempFile

import com.google.common.io.Files; //导入方法依赖的package包/类
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());
}
 
开发者ID:mit-cml,项目名称:appinventor-extensions,代码行数:11,代码来源:TempFilesTest.java

示例13: getContents

import com.google.common.io.Files; //导入方法依赖的package包/类
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;
	
}
 
开发者ID:rockitconsulting,项目名称:test.rockitizer,代码行数:13,代码来源:FileUtils.java

示例14: getUtfReader

import com.google.common.io.Files; //导入方法依赖的package包/类
/**
 * 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);
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:69,代码来源:XmlUtils.java

示例15: main

import com.google.common.io.Files; //导入方法依赖的package包/类
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();
    }
 
开发者ID:F1r3w477,项目名称:CustomWorldGen,代码行数:72,代码来源:GenDiffSet.java


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