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

The following are Jave code examples for showing how to use writeByteArrayToFile() of the org.apache.commons.io.FileUtils 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: TOSCAna   File: BaseDockerfileTest.java   View Source Code Vote up 8 votes
public String buildSHADockerfile() throws Exception {
    File bindir = new File(inputDir, "bin");
    bindir.mkdirs();
    byte[] data = new byte[1024 * 1024 * 10];
    new Random().nextBytes(data);

    FileUtils.writeByteArrayToFile(new File(bindir, "test.bin"), data);

    builder.run("apt update")
        .run("apt upgrade -y")
        .workdir("/hello")
        .copyFromCsar("bin", "bin", ".")
        .compressRunCommands()
        .entrypoint("sha256sum", "test.bin");

    builder.write();
    return DigestUtils.sha256Hex(data);
}
 
Example 2
Project: perfect-ssm   File: LoadImageController.java   View Source Code Vote up 7 votes
/**
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public Result upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
    ServletContext sc = request.getSession().getServletContext();
    String dir = sc.getRealPath("/upload");
    String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    String imgName = "";
    if (type.equals("jpg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
    } else if (type.equals("png")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
    } else if (type.equals("jpeg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
    } else {
        return null;
    }
    FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
    Result result = ResultGenerator.genSuccessResult();
    result.setData("upload/" + imgName);
    return result;
}
 
Example 3
Project: flow-platform   File: CredentialControllerTest.java   View Source Code Vote up 7 votes
@Test
public void should_download_success() throws Exception {
    String response = performRequestWith200Status(get("/credentials"));
    Credential[] credentials = Jsonable.parseArray(response, Credential[].class);
    Assert.assertEquals(4, credentials.length);

    response = performRequestWith200Status(get("/credentials/rsa-credential"));
    Assert.assertNotNull(response);

    // when: get download file
    MvcResult result = mockMvc.perform(get("/credentials/rsa-credential/download")).andExpect(status().isOk())
        .andReturn();

    File file = new File(String.valueOf(Paths.get(workspace.toString(), "test.zip")));
    FileUtils.writeByteArrayToFile(file, result.getResponse().getContentAsByteArray());

    // then: response is not null
    Assert.assertNotNull(response);

    // then: file is exists
    Assert.assertEquals(true, file.exists());
    ZipFile zipFile = new ZipFile(file);

    // them: zipfile has two files
    Assert.assertEquals(2, zipFile.size());
}
 
Example 4
Project: ros_android_bag   File: RecordLauncher.java   View Source Code Vote up 7 votes
private File copyRecordExecutableToFs(Context context, InputStream recordResource) throws IOException {
    byte[] recordBytes = IOUtils.toByteArray(recordResource);
    File recordFile = new File(context.getCacheDir(), "ros_android_bag_record");

    if (recordFile.exists()) recordFile.delete();

    FileUtils.writeByteArrayToFile(recordFile, recordBytes);

    boolean result = recordFile.setExecutable(true);
    if (result == false) {
        String errorText = "Could not set executable flag to " + recordFile.toString();
        Log.e(Common.LOG_TAG, errorText);
        throw new IllegalStateException(errorText);
    }
    return recordFile;
}
 
Example 5
Project: buenojo   File: ImageResourceService.java   View Source Code Vote up 7 votes
private File createTempFile(byte[] image, String fileExtension, String fileName,
		String completeFileName) throws IOException, BuenOjoFileException {
	File newTempFile =File.createTempFile(fileName, fileExtension);

	//write temp file
	try {
		FileUtils.writeByteArrayToFile(newTempFile, image);
	} catch (IOException e) {
		//clean up previous file
		log.error(e.getMessage());
		String message = "no se puedo guardar archivo temporal para el archivo:"+completeFileName;
		log.error(message);
		throw new BuenOjoFileException(message);

	}
	return newTempFile;
}
 
Example 6
Project: TOSCAna   File: TransformationControllerTest.java   View Source Code Vote up 7 votes
@Test
public void retrieveArtifact() throws Exception {
    preInitNonCreationTests();

    File dummyFile = new File(tmpdir, "test.bin");
    dummyFile.delete();
    byte[] data = ByteArrayUtils.generateRandomByteArray(new Random(123), 2048);
    FileUtils.writeByteArrayToFile(dummyFile, data);

    when(csarService.getCsar(VALID_CSAR_NAME).get().getTransformation(VALID_PLATFORM_NAME).get().getTargetArtifact())
        .thenReturn(Optional.of(new TargetArtifact(dummyFile)));

    mvc.perform(
        get(GET_ARTIFACTS_VALID_URL)
    )
        .andExpect(status().is(200))
        .andExpect(content().contentType("application/octet-stream"))
        .andExpect(content().bytes(data))
        .andReturn();
}
 
Example 7
Project: cloud-portal   File: VirtualMachineController.java   View Source Code Vote up 7 votes
private static File writeMultipartFile(MultipartFile multipartFile) {

		File file = null;

		try {
			if (!multipartFile.isEmpty()) {

				String multipartFileName = multipartFile.getOriginalFilename();
				String prefix = FilenameUtils.getBaseName(multipartFileName);
				String suffix = FilenameUtils.getExtension(multipartFileName);
				file = File.createTempFile(prefix, suffix);

				FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
			}
		}
		catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

		return file;
	}
 
Example 8
Project: cloudup   File: CloudupTestUtils.java   View Source Code Vote up 7 votes
public static int createTestFiles(File sourceDir, int size)
    throws IOException{
  File subdir = new File(sourceDir, "subdir");
  int expected = 0;
  mkdirs(subdir);
  File top = new File(sourceDir, "top");
  FileUtils.write(top, "toplevel");
  expected++;
  for (int i = 0; i < size; i++) {
    String text = String.format("file-%02d", i);
    File f = new File(subdir, text);
    FileUtils.write(f, f.toString());
  }
  expected += size;

  // and write the largest file
  File largest = new File(subdir, "largest");
  FileUtils.writeByteArrayToFile(largest,
      ContractTestUtils.dataset(8192, 32, 64));
  expected++;
  return expected;
}
 
Example 9
Project: springMvc4.x-project   File: UploadController.java   View Source Code Vote up 7 votes
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String upload(MultipartFile file) {// ①

	try {
		FileUtils.writeByteArrayToFile(new File("f:/upload/" + file.getOriginalFilename()),file.getBytes()); // ②
		return "ok";
	} catch (IOException e) {
		e.printStackTrace();
		return "wrong";
	}
}
 
Example 10
Project: atlas   File: CodeInjectByJavassist.java   View Source Code Vote up 7 votes
/**
 * Inject replacement operations for class files in the specified folder
 *
 * @param pool
 * @param folder
 * @param outFolder
 * @return
 * @throws IOException
 * @throws CannotCompileException
 * @throws NotFoundException
 * @throws Exception
 */
public static List<String> injectFolder(ClassPool pool,
                                        File folder,
                                        File outFolder,
                                        InjectParam injectParam) throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    if (folder.exists() && folder.isDirectory()) {
        Collection<File> classFiles = FileUtils.listFiles(folder, new String[] {"class"}, true);
        for (File classFile : classFiles) {
            String className = toRelative(folder, classFile.getAbsolutePath());
            File outClassFile = new File(outFolder, className);
            outClassFile.getParentFile().mkdirs();
            className = StringUtils.replace(className, File.separator, ".");
            className = className.substring(0, className.length() - 6);
            byte[] codes;

            codes = inject(pool, className, injectParam);
            FileUtils.writeByteArrayToFile(outClassFile, codes);

        }
    }
    return errorFiles;
}
 
Example 11
Project: Notebook   File: SyncFragment.java   View Source Code Vote up 6 votes
private void sync() {
	File tempFile = new File(Constants.CONFIG_TEMP_DB);
	if(!tempFile.exists()){
		DialogHelper.alert("����", "ͬ���ļ������ڣ��������غ���ͬ����");
		return;
	}
	progressbar.setVisible(true);
	progressbar.setProgress(-1f);
	progressbar.setProgress(0.5f);
	progressbar.setProgress(-1f);
	iv_down.setDisable(true);
	iv_sync.setDisable(true);

	String projectDir = System.getProperty("user.dir");
	File destFile = new File(projectDir,"notebook.db");

	try {
		byte[] data = FileUtils.readFileToByteArray(tempFile);
		FileUtils.writeByteArrayToFile(destFile, data);
	} catch (IOException e) {
		e.printStackTrace();
		DialogHelper.alert("Error", e.toString());
	}
	progressbar.setProgress(1f);
	iv_down.setDisable(false);
	iv_sync.setDisable(false);
	DialogHelper.alert("Success", "ͬ���ɹ���-> \r\n" + tempFile.getAbsolutePath() + " �ѱ��ƶ��� " + projectDir);
}
 
Example 12
Project: crawler   File: WindowUtil.java   View Source Code Vote up 6 votes
public static void taskScreenShot(WebDriver driver,File saveFile){
	if(saveFile.exists()){
		saveFile.delete();
	}
	byte[] src=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);//.FILE);linux下非root用户,java创建临时文件存在问题
	log.info("截图文件字节长度"+src.length);
	try {
		FileUtils.writeByteArrayToFile(saveFile, src);
	} catch (IOException e) {
		e.printStackTrace();
		log.error("截图写入失败",e);
	}
}
 
Example 13
Project: java_springboot   File: UploadController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/upload", method = RequestMethod.POST)
//使用MultipartFile 接收文件
public @ResponseBody
String upload(MultipartFile file) {
    try {
        String file_name = file.getOriginalFilename();
        FileUtils.writeByteArrayToFile(new File("d:/ssh/" + file.getOriginalFilename()), file.getBytes());
        return "ok";
    } catch (IOException e) {
        e.printStackTrace();
        return "wrong";
    }
}
 
Example 14
Project: TOSCAna   File: SwaggerAPIDownloadIT.java   View Source Code Vote up 6 votes
@Test
public void downloadSwaggerAPI() throws Exception {
    String url = getHttpUrl() + "v2/api-docs";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    String result = client.newCall(request).execute().body().string();
    FileUtils.writeByteArrayToFile(new File(SWAGGER_OUTPUT_DIR), result.getBytes());
}
 
Example 15
Project: tifoon   File: ReportFileIOServiceImpl.java   View Source Code Vote up 6 votes
@Override
public void saveFile(@NonNull final String _filename,
                     @NonNull final byte[] _data) {
    try {
        FileUtils.writeByteArrayToFile(new File(_filename), _data);
    } catch (IOException _e) {
        log.error("Failed to save report file", _e);
    }
}
 
Example 16
Project: xiushangzhuang   File: UploadController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public @ResponseBody String upload(MultipartFile file) {
    try {
        FileUtils.writeByteArrayToFile(new File("/"+file.getOriginalFilename()),file.getBytes());
        return "ok";
    } catch (IOException e) {
        e.printStackTrace();
        return "wrong";
    }
}
 
Example 17
Project: springMvc4.x-project   File: UploadController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String upload(MultipartFile file) {// ①

	try {
		FileUtils.writeByteArrayToFile(new File("f:/upload/" + file.getOriginalFilename()),file.getBytes()); // ②
		return "ok";
	} catch (IOException e) {
		e.printStackTrace();
		return "wrong";
	}
}
 
Example 18
Project: Thrush   File: LoginTest.java   View Source Code Vote up 5 votes
@Test
public void test2() throws IOException {
    byte[] bytes = HttpRequest.loginCaptchaImage();
    FileUtils.writeByteArrayToFile(new File("/Users/eddy/Desktop/image.jpg"), bytes);
}
 
Example 19
Project: osc-core   File: BackupService.java   View Source Code Vote up 5 votes
void writeEncryptedBackupFile(String backupFileName, byte[] encryptedBackupFileBytes) throws IOException {
	FileUtils.writeByteArrayToFile(getEncryptedBackupFile(backupFileName), encryptedBackupFileBytes);
}
 
Example 20
Project: osc-core   File: BackupData.java   View Source Code Vote up 5 votes
public File writeBackupZipFile(String filePath) throws IOException {
    File backupZipFile = new File(FilenameUtils.removeExtension(filePath) + BackupFileService.EXT_ZIP_BACKUP);
    FileUtils.writeByteArrayToFile(backupZipFile, dbData);
    return backupZipFile;
}