Java Code Examples for org.apache.commons.io.FileUtils#readFileToByteArray()

The following examples show how to use org.apache.commons.io.FileUtils#readFileToByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PcapMerger.java    From opensoc-streaming with Apache License 2.0 6 votes vote down vote up
/**
 * The main method.
 * 
 * @param args
 *          the arguments
 * 
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
  byte[] b1 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.1.pcap"));
  byte[] b2 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.2.pcap"));
  byte[] b3 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.3.pcap"));

  ByteArrayOutputStream boas = new ByteArrayOutputStream(); // $codepro.audit.disable
                                                            // closeWhereCreated
  PcapMerger.merge(boas, b1, b2, b3);

  FileUtils.writeByteArrayToFile(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.automerged.1.2.pcap"),
      boas.toByteArray(), false);

}
 
Example 2
Source File: PcapMerger.java    From metron with Apache License 2.0 6 votes vote down vote up
/**
 * The main method.
 * 
 * @param args
 *          the arguments
 * 
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
  byte[] b1 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.1.pcap"));
  byte[] b2 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.2.pcap"));
  byte[] b3 = FileUtils.readFileToByteArray(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.3.pcap"));

  ByteArrayOutputStream boas = new ByteArrayOutputStream(); // $codepro.audit.disable
                                                            // closeWhereCreated
  PcapMerger.merge(boas, b1, b2, b3);

  FileUtils.writeByteArrayToFile(new File(
      "/Users/sheetal/Downloads/constructedTcpDump.automerged.1.2.pcap"),
      boas.toByteArray(), false);

}
 
Example 3
Source File: NumpyFormatTests.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void readNumpyCorruptHeader1() throws Exception {
    File f = testDir.newFolder();

    File fValid = new ClassPathResource("numpy_arrays/arange_3,4_float32.npy").getFile();
    byte[] numpyBytes = FileUtils.readFileToByteArray(fValid);
    for( int i=0; i<10; i++ ){
        numpyBytes[i] = 0;
    }
    File fCorrupt = new File(f, "corrupt.npy");
    FileUtils.writeByteArrayToFile(fCorrupt, numpyBytes);

    INDArray exp = Nd4j.arange(12).castTo(DataType.FLOAT).reshape(3,4);

    INDArray act1 = Nd4j.createFromNpyFile(fValid);
    assertEquals(exp, act1);

    INDArray probablyShouldntLoad = Nd4j.createFromNpyFile(fCorrupt); //Loads fine
    boolean eq = exp.equals(probablyShouldntLoad); //And is actually equal content
}
 
Example 4
Source File: ConfigTest.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
@Test
  public void shouldUpdateSwiftSettingPreferredRegion() throws IOException {
  	
HasSwiftSettings swiftSettings = Configuration.INSTANCE.getSwiftSettings() ;
assertTrue (50000000 == swiftSettings.getSegmentationSize()) ;
assertTrue (swiftSettings.hideSegmentsContainers()) ;
assertTrue (swiftSettings.getPreferredRegion() == null) ;

byte[] initFileContents = FileUtils.readFileToByteArray (configSettingFile) ;

String newRegion = "reg" ;

SwiftParameters newParameters = new SwiftParameters.Builder(swiftSettings.getSegmentationSize(), swiftSettings.hideSegmentsContainers(), newRegion).build() ;
Configuration.INSTANCE.updateSwiftParameters(newParameters);

assertTrue (newRegion.equals(swiftSettings.getPreferredRegion())) ;

byte[] updatedFileContents = FileUtils.readFileToByteArray (configSettingFile) ;
assertFalse(Arrays.equals(updatedFileContents, initFileContents)) ;
  }
 
Example 5
Source File: GemFireXDDataExtractorDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void corruptFile(File file) throws IOException {
  byte[] fileBytes = FileUtils.readFileToByteArray(file);
  if (fileBytes != null && fileBytes.length > 0) {
    getLogWriter().info("#SB Corrupting the file : " + file.getCanonicalPath());

    for (int i=0; i<fileBytes.length; i++) {
      fileBytes[i] = (byte) (fileBytes[i]>>2);
    }
  }
  FileUtils.writeByteArrayToFile(file, fileBytes, false);
}
 
Example 6
Source File: ModerationImageContentDemo.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	ModerationImageContentDemo tool = new ModerationImageContentDemo();
	byte[] imageBytes = tool.downloadUrl("https://obs-ch-sdk-sample.obs.cn-north-1.myhuaweicloud.com/terrorism.jpg");
	tool.imageContentCheck(imageBytes);
	tool.imageAntiporn(imageBytes);

	imageBytes = FileUtils.readFileToByteArray(new File("data/moderation-demo-1.jpg"));
	tool.imageContentCheck(imageBytes);
	tool.imageAntiporn(imageBytes);
}
 
Example 7
Source File: TestEotReader.java    From FontVerter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void givenEotFont_whenHeaderRead_thenHeaderObjHasVersion() throws Exception {
    byte[] data = FileUtils.readFileToByteArray(new File(TestUtils.TEST_PATH + "/eot/arial.eot"));

    EotFont font = new EotFont();
    font.read(data);

    Assert.assertEquals(EotHeader.VERSION_TWO, font.getHeader().version);
}
 
Example 8
Source File: DexChecker.java    From DexExtractor with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isOdexFileFile(File file) throws IOException {
	// if (file.getAbsolutePath().endsWith(".read.dex")) {
	//
	// return false;
	// }
	byte[] datas = FileUtils.readFileToByteArray(file);

		if (datas != null && datas.length > 64 && datas[0] == 'd' && datas[1] == 'e' && datas[2] == 'y') {
			System.out.println((char) datas[0] + " xxxisOdexFileFilexxx " + (char) datas[1] + (char) datas[2]);
		return true;
	}
	return false;
}
 
Example 9
Source File: CommonLoadUploadFileAction.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private void loadData(File file) throws ServiceException, Exception {
	if (StringUtils.isBlank(this.oid)) {
		return;
	}
	DefaultResult<SysUploadVO> result = this.sysUploadService.findForNoByteContent(this.oid);
	if (result.getValue()==null) {
		throw new ControllerException(result.getSystemMessage().getValue());
	}		
	SysUploadVO uploadData = result.getValue();
	if (YesNo.YES.equals(uploadData.getIsFile())) {
		file = UploadSupportUtils.getRealFile(this.oid);
		if (!file.exists()) {
			return;
		}
		this.inputStream = new ByteArrayInputStream( FileUtils.readFileToByteArray(file) );
		this.filename = file.getName();
	} else {
		this.inputStream = new ByteArrayInputStream( UploadSupportUtils.getDataBytes(this.oid) );			
		this.filename = UploadSupportUtils.generateRealFileName(uploadData.getShowName());
	}
	if ("view".equals(this.type)) {
		if (file!=null) {
			try {
				this.contentType = FSUtils.getMimeType(file);
			} catch (Exception e) {
				logger.warn( e.getMessage().toString() );
			}				
		} else {
			this.contentType = FSUtils.getMimeType(uploadData.getShowName());
		}
	}		
	if (!StringUtils.isAsciiPrintable(result.getValue().getShowName())) {		
		String userAgent = super.defaultString(super.getHttpServletRequest().getHeader("User-Agent")).toLowerCase();
		if (userAgent.indexOf("firefox")==-1) { // for chrome or other browser.
			this.filename = URLEncoder.encode(result.getValue().getShowName(), Constants.BASE_ENCODING);				
		}
		return;
	}
	this.filename = result.getValue().getShowName();		
}
 
Example 10
Source File: PerformanceTest.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 上传测试文件
 *
 * @return
 * @throws IOException
 */
private StorePath uploadFile() throws IOException {
    URL path = PerformanceTest.class.getResource(TestConstants.PERFORM_FILE_PATH);
    byte[] bytes = FileUtils.readFileToByteArray(new File(path.getPath()));
    return storageClient.uploadFile(null, new ByteArrayInputStream(bytes),
            bytes.length, "jpg");
}
 
Example 11
Source File: BasicDBCoreObservableTest.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Test
public void createDocument_bodyOnly_success() throws Exception {

    File location = new File(database_dir, "test");
    File extensionsLocation = new File(location, "extensions");
    this.core = new DatabaseImpl(location, extensionsLocation, new NullKeyProvider());

    this.jsonData = FileUtils.readFileToByteArray(TestUtils.loadFixture(documentOneFile));
    this.bodyOne = new DocumentBodyImpl(jsonData);

    this.jsonData = FileUtils.readFileToByteArray(TestUtils.loadFixture(documentTwoFile));
    this.bodyTwo = new DocumentBodyImpl(jsonData);

    this.testObserver = new TestObserver(core);
    this.core.getEventBus().register(testObserver);

    Assert.assertEquals(-1L, testObserver.getSequence());

    DocumentRevision doc1Mut = new DocumentRevision();
    doc1Mut.setBody(bodyOne);
    DocumentRevision doc1 = core.create(doc1Mut);
    Assert.assertNotNull(doc1);
    Assert.assertEquals(1L, core.getLastSequence());
    Assert.assertEquals(1L, testObserver.getSequence());

    DocumentRevision doc2Mut = new DocumentRevision();
    doc2Mut.setBody(bodyOne);
    DocumentRevision doc2 = core.create(doc2Mut);
    Assert.assertNotNull(doc2);
    Assert.assertEquals(2L, core.getLastSequence());
    Assert.assertEquals(2L, testObserver.getSequence());

    DocumentRevision doc1_1Mut = doc1;
    doc1_1Mut.setBody(bodyTwo);
    DocumentRevision doc1_1 = core.update(doc1_1Mut);
    Assert.assertNotNull(doc1_1);
    Assert.assertEquals(3L, core.getLastSequence());
    Assert.assertEquals(3L, testObserver.getSequence());
}
 
Example 12
Source File: ConfigUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static boolean isFileEmpty(File file) {

        try {
            if (FileUtils.readFileToByteArray(file).length == 0) {
                LOG.info("The file: " + file.getName() + " is empty");
                return true;
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
 
Example 13
Source File: InstrumentTaskTest.java    From coroutines with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void mustInstrumentClasses() throws Exception {
    byte[] inputContent = readZipFromResource("NormalInvokeTest.zip").get("NormalInvokeTest.class");
    
    File inputDir = null;
    File outputDir = null;
    try {
        // create folders
        inputDir = Files.createTempDirectory(getClass().getSimpleName()).toFile();
        outputDir = Files.createTempDirectory(getClass().getSimpleName()).toFile();
        
        // write out
        File inputClass = new File(inputDir, "NormalInvokeTest.class");
        FileUtils.writeByteArrayToFile(inputClass, inputContent);
        
        // setup
        fixture.setSourceDirectory(inputDir);
        fixture.setTargetDirectory(outputDir);
        fixture.setClasspath("");
        
        // execute plugin
        fixture.execute();
        
        // read back in
        File outputClass = new File(outputDir, "NormalInvokeTest.class");
        byte[] outputContent = FileUtils.readFileToByteArray(outputClass);
        
        // test
        assertTrue(outputContent.length > inputContent.length);
    } finally {
        if (inputDir != null) {
            FileUtils.deleteDirectory(inputDir);
        }
        
        if (outputDir != null) {
            FileUtils.deleteDirectory(outputDir);
        }
    }
}
 
Example 14
Source File: NoopServlet.java    From wt1 with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
	ServletContext ctx = config.getServletContext();

	try {
		File f = new File(ctx.getRealPath(PIXEL_PATH));
		pixelData = FileUtils.readFileToByteArray(f);
	} catch (IOException e) {
		logger.error("Failed to read pixel", e);
		throw new ServletException(e);
	}
}
 
Example 15
Source File: QRCodeDemo.java    From ais-sdk with Apache License 2.0 4 votes vote down vote up
private static void qrCodeDemo() throws IOException {
	//
	// 1. 在ClientContextUtils类中, 配置好访问AIS服务的基本信息, 
	// 然后,在此处生成对应的一个客户端连接对象
	// 
	AisAccess service = new AisAccess(ClientContextUtils.getAuthInfo());
	
	//
	// 1.a 此处支持使用代理方式访问AIS服务,用于不能直接访问华为云官网服务的情况, 例如,内网网络。
	// 如果使用此处方式,需要同时在ClientContextUtils中,配置相应的代理服务器的参数类(ProxyHostInfo)
	//
	//AisAccess service = new AisAccessWithProxy(ClientContextUtils.getAuthInfo(), ClientContextUtils.getProxyHost());
	
	try {
		//
		// 2.构建访问二维码识别的使用示例函数服务需要的参数
		//
		String uri = "/v1.0/ocr/qr-code";

		byte[] fileData = FileUtils.readFileToByteArray(new File("data/qr-code-demo.jpg"));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);
		
		
		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");
		
		// 3.传入二维码识别服务对应的uri参数, 传入二维码识别服务需要的参数,
		// 该参数主要通过JSON对象的方式传入, 使用POST方法调用服务
		HttpResponse response = service.post(uri, stringEntity);
		
		// 4.验证服务调用返回的状态是否成功,如果为200, 为成功, 否则失败。
		ResponseProcessUtils.processResponseStatus(response);
		
		// 5.处理服务返回的字符流。
		ResponseProcessUtils.processResponse(response);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {

		// 6.使用完毕,关闭服务的客户端连接
		service.close();
	}
}
 
Example 16
Source File: TestFileAgent.java    From Hive2Hive with MIT License 4 votes vote down vote up
@Override
public byte[] readCache(String name) throws IOException {
	return FileUtils.readFileToByteArray(new File(root, name));
}
 
Example 17
Source File: ImageServiceTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddImageToRepository() throws Exception {

    mockery.checking(new Expectations() {{
        allowing(mediaFileNameStrategyResolver).getMediaFileNameStrategy(Constants.PRODUCT_IMAGE_REPOSITORY_URL_PATTERN);
        will(returnValue(mediaFileNameStrategy));
        allowing(languageService).getSupportedLanguages();
        will(returnValue(Arrays.asList("en", "uk", "ru")));
    }});

    imageService = new ImageServiceImpl(seoImageDao, mediaFileNameStrategyResolver, "50x150", 255, 255, 255, false, 50, true, new IOProvider() {
        @Override
        public boolean supports(final String uri) {
            return true;
        }

        @Override
        public boolean exists(final String uri, final Map<String, Object> context) {
            return new File(uri).exists();
        }

        @Override
        public String path(final String uri, final String subPath, final Map<String, Object> context) {
            return new File(uri, subPath).toURI().toString();
        }

        @Override
        public String nativePath(final String uri, final Map<String, Object> context) {
            return null;
        }

        @Override
        public List<IOItem> list(final String uri, final Map<String, Object> context) {
            return Collections.emptyList();
        }

        @Override
        public boolean isNewerThan(final String uriToCheck, final String uriToCheckAgainst, final Map<String, Object> context) {
            return false;
        }

        @Override
        public byte[] read(final String uri, final Map<String, Object> context) throws IOException {
            return FileUtils.readFileToByteArray(new File(uri));
        }

        @Override
        public void write(final String uri, final byte[] content, final Map<String, Object> context) throws IOException {
            FileUtils.writeByteArrayToFile(new File(uri), content);
        }

        @Override
        public void delete(final String uri, final Map<String, Object> context) throws IOException {
            assertTrue(new File(uri).delete());
        }
    });

    final String tmpFileName = "target/test/resources/some-seo-image-name_PRODUCT1.jpeg";
    byte[] image = Base64.decode(BASE64_ENCODED_JPEG_0);
    final String save1 = imageService.addImageToRepository(tmpFileName, "PRODUCT1", image, Constants.PRODUCT_IMAGE_REPOSITORY_URL_PATTERN, "target/");
    final File destination1 = new File("target/product/P/PRODUCT1/" + save1);
    assertTrue(destination1.exists());
    assertTrue("At least some info must be in the file" , destination1.length() > 1000);
    image = Base64.decode(BASE64_ENCODED_JPEG_1);
    final String save2 = imageService.addImageToRepository(tmpFileName, "PRODUCT1", image, Constants.PRODUCT_IMAGE_REPOSITORY_URL_PATTERN, "target/");
    final File destination2 = new File("target/product/P/PRODUCT1/" + save2);
    assertTrue(destination2.exists());
    assertTrue("At least some info must be in the file" , destination2.length() > 1000);
    assertTrue(save1.equals(save2));
    mockery.assertIsSatisfied();
}
 
Example 18
Source File: DocumentRevsUtilsTest.java    From sync-android with Apache License 2.0 4 votes vote down vote up
private DocumentRevs getDocumentRevsFromFile(File file) throws IOException {
    byte[] data = FileUtils.readFileToByteArray(file);
    return JSONUtils.deserialize(data, DocumentRevs.class);
}
 
Example 19
Source File: LogSender.java    From desktop with GNU General Public License v3.0 4 votes vote down vote up
private void setRequest(HttpPut request, File logFile) throws IOException {
    byte[] zipFileByteArray = FileUtils.readFileToByteArray(logFile);
    ByteArrayEntity requestEntity = new ByteArrayEntity(zipFileByteArray);
    request.setEntity(requestEntity);
}
 
Example 20
Source File: FileUtil.java    From phone with Apache License 2.0 3 votes vote down vote up
/**
 * 读取文件字节
 * 
 * @param file
 * @return
 * @throws IOException
 */
public static byte[] readFileBytes(File file) throws IOException {
	if (file == null) {
		return null;
	}
	return FileUtils.readFileToByteArray(file);
}