Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

In this page you can find the example usage for java.io BufferedOutputStream write.

Prototype

@Override
public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte to this buffered output stream.

Usage

From source file:com.anthony.forumspring.controller.FileUploadController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody String uploadFildHander(@RequestParam(value = "name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {/*from   w  w w  .  jav a  2  s .co  m*/
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            //logger.info("Server File Location="
            //      + serverFile.getAbsolutePath());
            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:net.okjsp.imageloader.ImageFetcher.java

/**
 * Download a bitmap from a URL, write it to a disk and return the File pointer. This
 * implementation uses a simple disk cache.
 *
 * @param context The context to use// w  ww. j ava2  s . c  om
 * @param urlString The URL to fetch
 * @return A File pointing to the fetched bitmap
 */
public static File downloadBitmap(Context context, String urlString) {
    final File cacheDir = DiskLruCache.getDiskCacheDir(context, HTTP_CACHE_DIR);

    final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir, HTTP_CACHE_SIZE);

    final File cacheFile = new File(cache.createFilePath(urlString));

    if (cache.containsKey(urlString)) {
        if (BuildConfig.DEBUG && DEBUG_LOG) {
            Log.d(TAG, "downloadBitmap - found in http cache - " + urlString);
        }
        return cacheFile;
    }

    if (BuildConfig.DEBUG && DEBUG_LOG) {
        Log.d(TAG, "downloadBitmap - downloading - " + urlString);
    }

    ImageLoaderUtils.disableConnectionReuseIfNecessary();
    BufferedOutputStream out = null;
    InputStream in = null;
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(urlString);

    try {
        if (DEBUG_LOG)
            Log.d(TAG, "getRequest:" + getRequest.toString());
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            in = new BufferedInputStream(entity.getContent(), ImageLoaderUtils.IO_BUFFER_SIZE);
        }
        out = new BufferedOutputStream(new FileOutputStream(cacheFile), ImageLoaderUtils.IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }

        in.close();
        in = null;

        return cacheFile;

    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            in = null;
        }

        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:br.edu.unidavi.restapp.FileUploadController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {//  www  .  j av  a  2  s. c  om
            String name = file.getOriginalFilename();
            System.out.println(name);
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded !";
        } catch (Exception e) {
            return "You failed to upload => " + e.getMessage();
        }
    } else {
        return "You failed to upload because the file was empty.";
    }
}

From source file:com.vtxii.smallstuff.etl.fileuploader.FileUploaderController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (false == file.isEmpty()) {
        try {/*from   w  w  w .ja v  a  2 s  . c o m*/
            // See if the file exists. If it does then another user
            // has uploaded a file of the same name at the same time
            // and it has not yet been processed.
            File newFile = new File(name);
            if (true == newFile.exists()) {
                String msg = "fail: file \"" + name + "\" exists and hasn't been processed";
                logger.error(msg);
                return msg;
            }

            // Write the file (this should be to the landing directory)
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
            stream.write(bytes);
            stream.close();

            // Process the file
            LandingManager.process(newFile, processor, null);

            return "success: loaded " + name;
        } catch (Exception e) {
            String msg = "fail: file \"" + name + "\" with error " + e.getMessage();
            logger.error(msg);
            return msg;
        }
    } else {
        return "fail: file \"" + name + "\" empty";
    }
}

From source file:edu.wfu.inotado.WinProfileServiceImplTest.java

public void testGetRemotePhotoAsByteArray() throws IOException {
    byte[] image = super.winProfileService
            .getRemotePhotoAsByteArray("https://win.wfu.edu/images/dir/JGBFBGK.JPG");
    assertNotNull(image);//from w  w w .  j  a v a  2  s . co m
    FileOutputStream output = new FileOutputStream(new File(outPutPhotoName));
    BufferedOutputStream bos = new BufferedOutputStream(output);
    bos.write(image);
    bos.close();

}

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();//  w  w 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:com.web.mavenproject6.controller.DocumentUploadController.java

@ResponseBody
@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public Object uploadMultipleFileHandler(@RequestParam("file") MultipartFile[] files) {
    System.out.print("PATH IS A:" + env.getProperty("upload.files.dir"));
    String buf = "";
    List<String> l = new ArrayList<>();
    for (MultipartFile file : files) {
        try {//from  www .j  a  v  a2s. co m
            byte[] bytes = file.getBytes();

            String rootPath = env.getProperty("upload.files.dir");

            File dir = new File(rootPath);
            if (!dir.exists()) {
                dir.mkdirs();
                dir.setWritable(true);
            }
            File serverFile = new File(rootPath + File.separator + file.getOriginalFilename());
            serverFile.createNewFile();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.err.println(file.getOriginalFilename());
            buf = XLSParser.parse(env.getProperty("upload.files.dir") + "\\" + file.getOriginalFilename());

            l.add(file.getOriginalFilename());
        } catch (Exception e) {

        }
    }
    // ModelAndView model = new ModelAndView("jsp/uploadedFiles");
    //model.addObject("list", l.toArray());
    // model.addObject("buffer",buf);
    //  return model;
    return buf;
}

From source file:com.turn.griffin.GriffinService.java

@RequestMapping(value = { "/localrepo", "/globalrepo" }, method = { RequestMethod.POST, RequestMethod.PUT })
public @ResponseBody String pushToRepo(@RequestParam(value = "blobname", required = true) String blobname,
        @RequestParam(value = "dest", required = true) String dest,
        @RequestParam(value = "file", required = true) MultipartFile file) {

    if (!StringUtils.isNotBlank(blobname)) {
        return "Blobname cannot be empty\n";
    }//w ww  . ja v a  2  s.  co  m

    if (!StringUtils.isNotBlank(dest)) {
        return "Dest cannot be empty\n";
    }

    try {
        File tempFile = File.createTempFile("gfn", null, null);
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(tempFile));
        stream.write(bytes);
        stream.close();
        module.get().syncBlob(blobname, dest, tempFile.getAbsolutePath());
        return String.format("Pushed file as blob %s to destination %s%n", blobname, dest);
    } catch (Exception e) {
        logger.error(String.format("POST request failed%n%s%n", ExceptionUtils.getStackTrace(e)));
        return String.format("Unable to push file as blob %s to destination %s%n", blobname, dest);
    } // TODO: Delete tempFile
}

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 {//www .  jav  a 2  s .  com
            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.springsecurity.plugin.util.ImageResizer.java

public File createFile(MultipartFile file, ServletContext context, String fileName) {
    try {//from www . j a  v a  2s.  c  om
        byte[] bytes = file.getBytes();
        // Creating the directory to store file
        String rootPath = context.getRealPath("");
        File dir = new File(rootPath + File.separator + MENU_IMG_FOLDER + File.separator + "Temp");
        if (!dir.exists())
            dir.mkdirs();
        String filePath = dir.getAbsolutePath() + File.separator + fileName;
        // Create the file on server
        File serverFile = new File(filePath);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();
        return serverFile;
    } catch (Exception e) {
        return null;
    }
}