List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:net.dfs.remote.filestorage.impl.StorageManagerImpl.java
/** * fileStorage will be responsible in storing the File object in the local * storage device. A notification indicating the name of the File object and the * remote machine's address will be sent to the {@link FileLocationTracker}. * <p>//from ww w .j a v a2s . c om * An OutPutStream of the FileObject will be saved in the local storage device. * IOException will be thrown on a failure. It returns no value. * * @param storeFile an object of the type {@link FileStorageModel} */ public void fileStorage(FileStorageModel storeFile) { try { String savePath = path + storeFile.fileName; BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath)); outputStream.write(storeFile.bytes, 0, storeFile.bytesRead); outputStream.flush(); outputStream.close(); log.debug("File " + storeFile.fileName + " saved to the disk"); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.datavec.api.records.reader.impl.SVMRecordWriterTest.java
@Test public void testWriter() throws Exception { String tempDir = System.getProperty("java.io.tmpdir"); InputStream is = new ClassPathResource("iris.dat").getInputStream(); assumeNotNull(is);/*from w w w . j a va2 s. c o m*/ File tmp = new File(tempDir, "iris.txt"); if (tmp.exists()) tmp.delete(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp)); IOUtils.copy(is, bos); bos.flush(); bos.close(); InputSplit split = new FileSplit(tmp); tmp.deleteOnExit(); RecordReader reader = new CSVRecordReader(); List<List<Writable>> records = new ArrayList<>(); reader.initialize(split); while (reader.hasNext()) { List<Writable> record = reader.next(); assertEquals(5, record.size()); records.add(record); } assertEquals(150, records.size()); File out = new File(tempDir, "iris_out.txt"); if (out.exists()) out.delete(); out.deleteOnExit(); RecordWriter writer = new SVMLightRecordWriter(out, true); for (List<Writable> record : records) writer.write(record); writer.close(); records.clear(); RecordReader svmReader = new SVMLightRecordReader(); InputSplit svmSplit = new FileSplit(out); svmReader.initialize(svmSplit); assertTrue(svmReader.hasNext()); while (svmReader.hasNext()) { List<Writable> record = svmReader.next(); assertEquals(5, record.size()); records.add(record); } assertEquals(150, records.size()); }
From source file:com.edgenius.core.util.ZipFileUtil.java
public static void expandZipToFolder(InputStream is, String destFolder) throws ZipFileUtilException { // got our directory, so write out the input file and expand the zip file // this is really a hack - write it out temporarily then read it back in again! urg!!!! ZipInputStream zis = new ZipInputStream(is); int count;/*from ww w. j a v a2 s . c om*/ byte data[] = new byte[BUFFER_SIZE]; ZipEntry entry = null; BufferedOutputStream dest = null; String entryName = null; try { // work through each file, creating a node for each file while ((entry = zis.getNextEntry()) != null) { entryName = entry.getName(); if (!entry.isDirectory()) { String destName = destFolder + File.separator + entryName; //It must sort out the directory information to current OS. //e.g, if zip file is zipped under windows, but unzip in linux. destName = FileUtil.makeCanonicalPath(destName); prepareDirectory(destName); FileOutputStream fos = new FileOutputStream(destName); dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } dest.flush(); IOUtils.closeQuietly(dest); dest = null; } else { String destName = destFolder + File.separator + entryName; destName = FileUtil.makeCanonicalPath(destName); new File(destName).mkdirs(); } } } catch (IOException ioe) { log.error("Exception occured processing entries in zip file. Entry was " + entryName, ioe); throw new ZipFileUtilException( "Exception occured processing entries in zip file. Entry was " + entryName, ioe); } finally { IOUtils.closeQuietly(dest); IOUtils.closeQuietly(zis); } }
From source file:com.pax.pay.trans.receipt.paperless.AReceiptEmail.java
private File Convert(Bitmap bm, String fileName) throws IOException { String path = ContextUtils.getFilesDir() + "/temp/"; File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdir();/* www . j a va 2 s . c o m*/ } File myCaptureFile = new File(path + fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); return myCaptureFile; }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
public static boolean removeZipEntry(File file, Pattern pattern, File targetFile) throws FileNotFoundException, IOException { byte[] buffer = new byte[1024]; java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetFile))); BufferedOutputStream bo = new BufferedOutputStream(out); InputStream inputStream;/* www . ja va2s . c o m*/ Enumeration enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enumeration.nextElement(); String name = zipEntry.getName(); if (pattern.matcher(name).find()) { continue; } out.putNextEntry(zipEntry); inputStream = zipFile.getInputStream(zipEntry); write(inputStream, out, buffer); bo.flush(); } closeQuitely(zipFile); closeQuitely(out); closeQuitely(bo); return true; }
From source file:de.berlios.jhelpdesk.web.ticket.UploadFileController.java
@RequestMapping(method = RequestMethod.POST) protected String processSubmit(@ModelAttribute("fileBean") FileUploadBean uploadedFile, @RequestParam("ticketstamp") String ticketstamp, ModelMap map, HttpSession session) { MultipartFile file = uploadedFile.getFile(); if (file != null) { File targetDir = fileUtils.createTmpDirForTicketstamp(ticketstamp); File targetFile = new File(targetDir, file.getOriginalFilename()); addPathToSession(session, targetDir.getAbsolutePath()); try {/*from ww w . j a v a2s . c o m*/ BufferedOutputStream buff = new BufferedOutputStream(new FileOutputStream(targetFile)); buff.write(uploadedFile.getFile().getBytes()); buff.flush(); buff.close(); } catch (Exception e) { log.error("Wystpi problem z przetworzeniem pliku.", e); // obsuga wyjtku? } } map.addAttribute("uploaded", Boolean.TRUE); return TICKETS_UPLOAD_VIEW; }
From source file:com.glaf.chart.util.ChartUtils.java
public static byte[] createChart(Chart chartModel, JFreeChart chart) { ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; try {//w ww.j ava 2 s . com baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); java.awt.image.BufferedImage bi = chart.createBufferedImage(chartModel.getChartWidth(), chartModel.getChartHeight()); if ("png".equalsIgnoreCase(chartModel.getImageType())) { EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); ServletUtilities.saveChartAsPNG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(), info, null); } else if ("jpeg".equalsIgnoreCase(chartModel.getImageType())) { EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); ServletUtilities.saveChartAsJPEG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(), info, null); } bos.flush(); baos.flush(); return baos.toByteArray(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { IOUtils.closeQuietly(baos); IOUtils.closeQuietly(bos); } }
From source file:au.org.ala.layers.grid.GridClassBuilder.java
public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException { File wktDir = new File(filePath); wktDir.mkdirs();//from ww w .j ava 2 s . c o m int[] wktMap = null; //track values for the SLD ArrayList<Integer> maxValues = new ArrayList<Integer>(); ArrayList<String> labels = new ArrayList<String>(); HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>(); Properties p = new Properties(); p.load(new FileReader(filePath + ".txt")); boolean mergeProperties = false; Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>(); Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>(); Map<String, Integer> translateValues = new HashMap<String, Integer>(); ArrayList<Integer> keys = new ArrayList<Integer>(); for (String key : p.stringPropertyNames()) { try { int k = Integer.parseInt(key); keys.add(k); //grouping of property file keys by value String value = p.getProperty(key); Set<Integer> klist = groupedKeys.get(value); if (klist == null) klist = new HashSet<Integer>(); else mergeProperties = true; klist.add(k); groupedKeys.put(value, klist); if (!translateValues.containsKey(value)) translateValues.put(value, translateValues.size() + 1); translateKeys.put(k, translateValues.get(value)); } catch (NumberFormatException e) { logger.info("Excluding shape key '" + key + "'"); } catch (Exception e) { logger.error(e.getMessage(), e); } } java.util.Collections.sort(keys); Grid g = new Grid(filePath); boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE; if (mergeProperties) { g.replaceValues(translateKeys); if (!new File(filePath + ".txt.old").exists()) FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old")); StringBuilder sb = new StringBuilder(); for (String value : translateValues.keySet()) { sb.append(translateValues.get(value)).append("=").append(value).append('\n'); } FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString()); return buildFromGrid(filePath); } if (generateWkt) { for (String name : groupedKeys.keySet()) { try { Set<Integer> klist = groupedKeys.get(name); String key = klist.iterator().next().toString(); int k = Integer.parseInt(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); if (klist.size() == 1) klist = null; logger.info("getting wkt for " + filePath + " > " + key); Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed( filePath + "," + key + "," + key, klist, wktMap); //write class wkt File zipFile = new File(filePath + File.separator + key + ".wkt.zip"); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry(key + ".wkt")); zos.write(((String) wktIndexed.get("wkt")).getBytes()); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(filePath + File.separator + key + ".wkt")); bos.write(((String) wktIndexed.get("wkt")).getBytes()); bos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("wkt written to file"); gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0); //store map wktMap = (int[]) wktIndexed.get("map"); //write wkt index FileWriter fw = null; try { fw = new FileWriter(filePath + File.separator + key + ".wkt.index"); fw.append((String) wktIndexed.get("index")); fw.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km) int minPolygonNumber = 0; int maxPolygonNumber = 0; RandomAccessFile raf = null; try { raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw"); String[] index = ((String) wktIndexed.get("index")).split("\n"); for (int i = 0; i < index.length; i++) { if (index[i].length() > 1) { String[] cells = index[i].split(","); int polygonNumber = Integer.parseInt(cells[0]); raf.writeInt(polygonNumber); //polygon number int polygonStart = Integer.parseInt(cells[1]); raf.writeInt(polygonStart); //character offset if (i == 0) { minPolygonNumber = polygonNumber; } else if (i == index.length - 1) { maxPolygonNumber = polygonNumber; } } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (raf != null) { try { raf.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //for SLD maxValues.add(gc.getMaxShapeIdx()); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(minPolygonNumber); gc.setMaxShapeIdx(maxPolygonNumber); logger.info("getting multipolygon for " + filePath + " > " + key); MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key); gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ",")); classes.put(k, gc); try { //write class kml zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".kml.zip")); zos.putNextEntry(new ZipEntry(key + ".kml")); Encoder encoder = new Encoder(new KMLConfiguration()); encoder.setIndenting(true); encoder.encode(mp, KML.Geometry, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("kml written to file"); final SimpleFeatureType TYPE = DataUtilities.createType("class", "the_geom:MultiPolygon,id:Integer,name:String"); FeatureJSON fjson = new FeatureJSON(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); SimpleFeature sf = featureBuilder.buildFeature(null); //write class geojson zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".geojson.zip")); zos.putNextEntry(new ZipEntry(key + ".geojson")); featureBuilder.add(mp); featureBuilder.add(k); featureBuilder.add(name); fjson.writeFeature(sf, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("geojson written to file"); //write class shape file File newFile = new File(filePath + File.separator + key + ".shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.FALSE); ShapefileDataStore newDataStore = null; try { newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(TYPE); newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); DefaultFeatureCollection collection = new DefaultFeatureCollection(); collection.addAll(features); featureStore.setTransaction(transaction); features.add(sf); featureStore.addFeatures(collection); transaction.commit(); transaction.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (newDataStore != null) { try { newDataStore.dispose(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".shp.zip")); //add .dbf .shp .shx .prj String[] exts = { ".dbf", ".shp", ".shx", ".prj" }; for (String ext : exts) { zos.putNextEntry(new ZipEntry(key + ext)); FileInputStream fis = null; try { fis = new FileInputStream(filePath + File.separator + key + ext); byte[] buffer = new byte[1024]; int size; while ((size = fis.read(buffer)) > 0) { zos.write(buffer, 0, size); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //remove unzipped files new File(filePath + File.separator + key + ext).delete(); } zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("shape file written to zip"); } catch (Exception e) { logger.error(e.getMessage(), e); } } catch (Exception e) { logger.error(e.getMessage(), e); } } //write polygon mapping g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres, g.yres, g.nrows, g.ncols); //copy the header file to get it exactly the same, but change the data type copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd"); } else { //build classes without generating polygons Map<Float, float[]> info = new HashMap<Float, float[]>(); for (int j = 0; j < keys.size(); j++) { info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN }); } g.getClassInfo(info); for (int j = 0; j < keys.size(); j++) { int k = keys.get(j); String key = String.valueOf(k); String name = p.getProperty(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); //for SLD maxValues.add(Integer.valueOf(key)); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(Integer.valueOf(key)); gc.setMaxShapeIdx(Integer.valueOf(key)); float[] stats = info.get(keys.get(j).floatValue()); //only include if area > 0 if (stats[0] > 0) { gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + "," + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " " + stats[2] + "))"); gc.setArea_km((double) stats[0]); classes.put(k, gc); } } } //write sld exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues, labels); writeProjectionFile(filePath + File.separator + "polygons.prj"); //write .classes.json ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filePath + ".classes.json"), classes); return classes; }
From source file:info.guardianproject.iocipher.camera.StillCameraActivity.java
@Override public void onPictureTaken(final byte[] data, Camera camera) { File fileSecurePicture;/*from ww w.j a v a2 s. c om*/ try { if (overlayView != null) overlayView.setBackgroundResource(R.color.flash); notifyUserImageWasSavedSuccessfully(); long mTime = System.currentTimeMillis(); fileSecurePicture = new File(mFileBasePath, "secure_image_" + mTime + ".jpg"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileSecurePicture)); out.write(data); out.flush(); out.close(); mResultList.add(fileSecurePicture.getAbsolutePath()); Intent intent = new Intent("new-media"); // You can also include some extra data. intent.putExtra("media", fileSecurePicture.getAbsolutePath()); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); Intent intentResult = new Intent().putExtra(MediaStore.EXTRA_OUTPUT, mResultList.toArray(new String[mResultList.size()])); setResult(Activity.RESULT_OK, intentResult); view.postDelayed(new Runnable() { @Override public void run() { overlayView.setBackgroundColor(Color.TRANSPARENT); resumePreview(); } }, 300); } catch (Exception e) { e.printStackTrace(); setResult(Activity.RESULT_CANCELED); } }
From source file:com.aurel.track.admin.customize.category.report.ReportBL.java
/** * Save the new template at given location(repository, project) * @param repository//from w ww .ja va2 s . co m * @param personID * @param project * @param templateName * @param uploadZip * @return an error meassage if exist */ public static void saveTemplate(Integer id, ZipInputStream zis) throws IOException { // specify buffer size for extraction final int BUFFER = 2048; // Open Zip file for reading File unzipDestinationDirectory = getDirTemplate(id); BufferedOutputStream dest = null; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { File destFile = new File(unzipDestinationDirectory, entry.getName()); if (destFile.exists()) { destFile.delete(); } // grab file's parent directory structure File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); int count; byte data[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.close(); }