List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data) throws IOException
From source file:com.intuit.tank.script.TestUploadBean.java
/** * Saves the script in the database.//from w ww . j a v a 2 s . com */ public String save() { UploadedFile item = getFile(); try { String fileName = item.getFileName(); fileName = FilenameUtils.getBaseName(fileName) + "-" + UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName); File parent = new File("uploads"); parent.mkdirs(); File f = new File(parent, fileName); LOG.info("Writing file to " + f.getAbsolutePath()); FileUtils.writeByteArrayToFile(f, item.getContents()); messages.info("Wrote file to " + f.getAbsolutePath()); } catch (Exception e) { messages.error(e.getMessage()); } return null; }
From source file:de.topobyte.largescalefileio.TestClosingFileInputStream.java
public void test(int n) throws IOException { files = new File[n]; for (int i = 0; i < n; i++) { files[i] = File.createTempFile("closing-fis", ".dat"); }/* w w w . j ava 2 s . c o m*/ allFiles.addAll(Arrays.asList(files)); ByteArrayGenerator generator = new ByteArrayGenerator(); byte[][] bytes = new byte[n][]; for (int i = 0; i < n; i++) { bytes[i] = generator.generateBytes(1024); } for (int i = 0; i < n; i++) { FileUtils.writeByteArrayToFile(files[i], bytes[i]); } ClosingFileInputStreamFactory factory = new SimpleClosingFileInputStreamFactory(); InputStream[] inputs = new InputStream[n]; for (int i = 0; i < n; i++) { inputs[i] = factory.create(files[i]); } byte[][] results = ReaderUtil.readInterleaved(inputs); for (int i = 0; i < n; i++) { Assert.assertArrayEquals(bytes[i], results[i]); } }
From source file:com.bandstand.web.SongsController.java
@PutChild public Song uploadSong(SongsRoot root, String newName, byte[] bytes) throws IOException { File fRoot = getContentRoot(); File content = new File(fRoot, UUID.randomUUID().toString()); FileUtils.writeByteArrayToFile(content, bytes); Song song = new Song(); song.setDisplayName(newName);/*from ww w .j av a 2s . c o m*/ song.setFileName(content.getAbsolutePath()); song.setBand(root.getEntity()); if (root.getEntity().getImages() == null) { root.getEntity().setImages(new ArrayList<Image>()); } root.getEntity().getSongs().add(song); SessionManager.session().save(song); SessionManager.session().save(root.getEntity()); return song; }
From source file:net.netheos.pcsapi.BytesIOTest.java
@Test public void testFileByteSource() throws Exception { String strContent = "This 1 file is the test content of a file byte source... (70 bytes)"; byte[] byteContent = strContent.getBytes(PcsUtils.UTF8); File tmpFile = new File(tmpDir, "byte_source.txt"); FileUtils.writeByteArrayToFile(tmpFile, byteContent); ByteSource bs = new FileByteSource(tmpFile); checkByteSource(bs, byteContent);//from ww w . ja va 2s . c om bs = new MemoryByteSource(byteContent); checkByteSource(bs, byteContent); }
From source file:de.micromata.genome.gwiki.tools.PatchJavaHeader.java
public static void patchFile(File file) { try {//from w w w .j a v a2 s .c o m byte[] data = FileUtils.readFileToByteArray(file); int ofs = skipComments(data); byte[] newData = new byte[data.length - ofs + headerBytes.length]; System.arraycopy(headerBytes, 0, newData, 0, headerBytes.length); System.arraycopy(data, ofs, newData, headerBytes.length, data.length - ofs); // String nf = new String(newData); // System.out.println("\n\n\n" + nf); FileUtils.writeByteArrayToFile(file, newData); } catch (IOException ex) { throw new RuntimeIOException(ex); } }
From source file:controllers.FreeOptionController.java
@RequestMapping("/updateFromXml") public String updateFromXml(Map<String, Object> model, @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) { if (file == null || file.isEmpty()) { ras.addFlashAttribute("error", "File not found"); } else {//from w w w.j av a2 s . c o m File newFile = new File("/usr/local/etc/Option"); if (newFile.exists()) { newFile.delete(); } try { FileUtils.writeByteArrayToFile(newFile, file.getBytes()); freeOptionService.updateFromXml(newFile); ras.addFlashAttribute("error", freeOptionService.getResult().getErrors()); } catch (Exception e) { ras.addFlashAttribute("error", "updateFromXml " + StringAdapter.getStackTraceException(e)); } if (newFile.exists()) { newFile.delete(); } } return "redirect:/FreeOption/show"; }
From source file:filehandling.FilePreprocessor.java
public static List<FileData> extractMDFilesFromXMLEmbedding(byte[] bytes, String basename, String extension) { List<FileData> returnList = new ArrayList<FileData>(); try {/*w w w. j a v a 2s . c om*/ FileUtils.writeByteArrayToFile(new File("/tmp/debugData/instreamBeforeExtraction.xml"), bytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(bytes))); if (Master.DEBUG_LEVEL > Master.LOW) { System.out.println("Root element: " + doc.getDocumentElement().getNodeName()); } NodeList entryElements = doc.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "entry"); for (int i = 0; i < entryElements.getLength(); i++) { Element entryElement = (Element) entryElements.item(i); FileData fd = null; /* * First try to find a <link> element pointing to Metadata as * this should be included by default */ if (fd == null) { NodeList linkElements = entryElement.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "link"); String iso19139Link = null; String iso19139_2Link = null; for (int j = 0; j < linkElements.getLength(); j++) { Element linkElement = (Element) linkElements.item(j); String relAttrValue = linkElement.getAttribute("rel"); String typeAttributeValue = linkElement.getAttribute("type"); if (relAttrValue != null && relAttrValue.equals("alternate") && typeAttributeValue != null) { switch (typeAttributeValue) { case "application/vnd.iso.19139+xml": iso19139Link = linkElement.getAttribute("href"); break; case "application/vnd.iso.19139-2+xml": iso19139_2Link = linkElement.getAttribute("href"); break; } } } /* iso19139-2 gets priority */ String url = iso19139_2Link != null ? iso19139_2Link : iso19139Link; if (url != null) { try (InputStream is = FileFetcher.fetchFileFromUrl(url)) { Document doc2 = dBuilder.parse(new InputSource(is)); fd = processMDList(doc2.getDocumentElement(), extension, url); } } } /* * Fallback to finding Metadata embedded directly in <entry>. * There will be either MI_Metadata or MD_Metadata, not both */ if (fd == null) { fd = processMDList(entryElement.getElementsByTagName("gmi:MI_Metadata").item(0), extension, null); } if (fd == null) { fd = processMDList(entryElement.getElementsByTagName("gmd:MD_Metadata").item(0), extension, null); } if (fd != null) { returnList.add(fd); } } } catch (Exception e) { // TODO: handle exception if (Master.DEBUG_LEVEL > Master.LOW) System.out.println(e.getLocalizedMessage()); GUIrefs.displayAlert("Error in FilePreprocessor.extractMDFilesFromXMLEmbedding" + StringUtilities.escapeQuotes(e.getMessage())); } return returnList; }
From source file:es.urjc.mctwp.bbeans.research.upload.FileUploadBean.java
public String accUploadFiles() throws IOException { List<File> files = new ArrayList<File>(); String base = getSession().getAbsoluteThumbDir(); String action = "uploadSuccess"; //Get uploaded files wrote to disk if (img1 != null) { File f = new File(FilenameUtils.concat(base, img1.getName())); FileUtils.writeByteArrayToFile(f, img1.getBytes()); files.add(f);//from w w w .j av a2 s.co m } if (img2 != null) { File f = new File(FilenameUtils.concat(base, img2.getName())); FileUtils.writeByteArrayToFile(f, img2.getBytes()); files.add(f); } Command cmd = getCommand(StoreTemporalImages.class); ((StoreTemporalImages) cmd).setFiles(files); runCommand(cmd); return action; }
From source file:io.hakbot.publishers.BasePublisher.java
/** * Writes the contents of the JobArtifact to the specified directory. Returns a * File object referencing the result, or null if something goes wrong. *///from w ww . j a va 2 s.c o m public File getResult(JobArtifact artifact, File directory) { try { String filename = artifact.getFilename(); if (StringUtils.isEmpty(filename)) { filename = job.getUuid() + ".result"; } final File result = new File(directory, filename).getAbsoluteFile(); FileUtils.writeByteArrayToFile(result, artifact.getContents()); addProcessingMessage(job, "Result written to: " + result.getPath()); return result; } catch (IOException e) { LOGGER.error("Unable to write result from job: " + job.getUuid()); LOGGER.error(e.getMessage()); addProcessingMessage(job, "Unable to write result to file"); addProcessingMessage(job, e.getMessage()); } return null; }
From source file:com.googlecode.dex2jar.test.V3Test.java
public static void doData(byte[] data, final File destDir) throws IOException { final int lineCount = 50; DexFileReader reader = new DexFileReader(data); V3InnerClzGather afa = new V3InnerClzGather(); final List<String> exes = new ArrayList<String>(); reader.accept(afa, DexFileReader.SKIP_CODE | DexFileReader.SKIP_DEBUG); System.out.flush();// w ww. j a va2 s . c o m String logFileName = "target/v3.log." + System.currentTimeMillis(); final PrintWriter log = new PrintWriter(logFileName, "UTF-8"); System.out.write(String.format("%05d ", 0).getBytes(UTF8)); reader.accept(new V3(afa.getClasses(), null, new ClassVisitorFactory() { int count = 0; @Override public ClassVisitor create(final String name) { return new ClassWriter(ClassWriter.COMPUTE_MAXS) { @Override public void visitEnd() { count++; try { super.visitEnd(); byte[] data = this.toByteArray(); FileUtils.writeByteArrayToFile(new File(destDir, name + ".class"), data); TestUtils.verify(new ClassReader(data), log); System.out.write('.'); } catch (Throwable e) { System.out.write('X'); exes.add(String.format("%05d %s - %s", count - 1, name, e.getMessage())); } if (count % lineCount == 0) { try { System.out.write(String.format("\n%05d ", count).getBytes(UTF8)); } catch (IOException e) { throw new RuntimeException(e); } } System.out.flush(); } }; } }, V3.REUSE_REGISTER | V3.TOPOLOGICAL_SORT | V3.OPTIMIZE_SYNCHRONIZED), DexFileReader.SKIP_DEBUG); System.out.flush(); System.out.println(); log.close(); if (exes.size() > 0) { StringBuilder sb = new StringBuilder("there are ").append(exes.size()) .append(" error(s) while translate\n"); for (String ln : exes) { sb.append(ln).append("\n"); } sb.append("details: ").append(logFileName).append("\n"); throw new RuntimeException(sb.toString()); } }