Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:org.anon.smart.smcore.test.channel.upload.TestUploadEvent.java

private String downloadFile(String file) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    String dwnFile = file + ".1";
    HttpGet httpget = new HttpGet("http://localhost:9020/errortenant/ErrorCases/DownloadEvent/" + file);
    HttpResponse response = httpclient.execute(httpget);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {/*from   w  ww  .j  a  v a2s  .  co m*/
            BufferedInputStream bis = new BufferedInputStream(instream);

            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(new File(projectHome + "/" + dwnFile)));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (RuntimeException ex) {
            httpget.abort();
            throw ex;
        } finally {
            instream.close();
        }
        httpclient.getConnectionManager().shutdown();
    }
    return dwnFile;
}

From source file:quanlyhocvu.api.web.controller.staff.ManagementStudentController.java

@RequestMapping(value = "nhap_hocsinh", headers = "content-type=multipart/*", method = RequestMethod.POST)
public @ResponseBody ModelAndView importHocSinh(
        @RequestParam(value = "danhSachHocSinh", required = false) MultipartFile danhSachHocSinh)
        throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    //        File file = new File(servletContext.getRealPath("/") + "/"
    //                    + filename);
    //String path = servletContext.getRealPath("/");                
    KhoiLopDTO khoiLop = mongoService.getKhoiLopByName("6");
    //System.out.println(request.getParameter("danhSachHocSinh"));
    //System.out.println(path);
    File temp_file = new File("uploaded.xls");
    byte[] bytes = danhSachHocSinh.getBytes();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(temp_file));
    stream.write(bytes);/*w ww.ja  va  2  s  .  c o m*/
    stream.close();
    System.out.println(danhSachHocSinh.getOriginalFilename());
    Workbook w;
    try {
        w = Workbook.getWorkbook(temp_file);
        //Get the first sheet
        Sheet sheet = w.getSheet(0);
        for (int i = 1; i < sheet.getRows(); i++) {
            HocSinhDTO hs = new HocSinhDTO();
            //Do columns co 6 cot nen se lay 6 cot
            Cell[] listCell = new Cell[7];
            for (int j = 0; j < 7; j++) {
                listCell[j] = sheet.getCell(j, i);
            }

            String hoTen = listCell[1].getContents();
            hs.sethoTen(hoTen);

            String gioiTinh = listCell[2].getContents();
            if (gioiTinh == "Nam") {
                hs.setgioiTinh(1);
            } else {
                hs.setgioiTinh(0);
            }

            String ngaySinh = listCell[3].getContents();
            Date ngaySinhDate = FunctionService.formatStringDateExcel(ngaySinh);
            hs.setngaySinh(ngaySinhDate);

            String ngayNhapHoc = listCell[4].getContents();
            Date ngayNhapHocDate = FunctionService.formatStringDateExcel(ngayNhapHoc);
            hs.setngayNhapHoc(ngayNhapHocDate);

            String diaChi = listCell[5].getContents();
            hs.setdiaChi(diaChi);

            String moTa = listCell[6].getContents();
            hs.setmoTa(moTa);
            hs.setKhoiLopHienTai(khoiLop);
            mongoService.insertStudent(hs);
        }
    } catch (BiffException ex) {
        java.util.logging.Logger.getLogger(ManagementStudentController.class.getName()).log(Level.SEVERE, null,
                ex);
    }
    return new ModelAndView("redirect:/staff/management/students/index", map);
}

From source file:com.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }//from  w  w  w  .  ja  v a 2 s .  c o m
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {

        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

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

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;/*from  w w  w.j  av a 2s. c  o m*/
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

From source file:SimpleFTP.java

/**
 * Sends a file to be stored on the FTP server. Returns true if the file
 * transfer was successful. The file is sent in passive mode to avoid NAT or
 * firewall problems at the client end./* w w  w.j  a v a2 s  .  co  m*/
 */
public synchronized boolean stor(InputStream inputStream, String filename) throws IOException {

    BufferedInputStream input = new BufferedInputStream(inputStream);

    sendLine("PASV");
    String response = readLine();
    if (!response.startsWith("227 ")) {
        throw new IOException("SimpleFTP could not request passive mode: " + response);
    }

    String ip = null;
    int port = -1;
    int opening = response.indexOf('(');
    int closing = response.indexOf(')', opening + 1);
    if (closing > 0) {
        String dataLink = response.substring(opening + 1, closing);
        StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
        try {
            ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
                    + tokenizer.nextToken();
            port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
        } catch (Exception e) {
            throw new IOException("SimpleFTP received bad data link information: " + response);
        }
    }

    sendLine("STOR " + filename);

    Socket dataSocket = new Socket(ip, port);

    response = readLine();
    if (!response.startsWith("125 ")) {
        //if (!response.startsWith("150 ")) {
        throw new IOException("SimpleFTP was not allowed to send the file: " + response);
    }

    BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
    output.flush();
    output.close();
    input.close();

    response = readLine();
    return response.startsWith("226 ");
}

From source file:com.jeans.iservlet.action.asset.AssetExportAction.java

private void export(HttpServletResponse resp) throws IOException {
    StringBuilder fn = new StringBuilder(getCurrentCompany().getName());
    Workbook wb = new XSSFWorkbook();
    if ("_hard".equals(type)) {
        fn.append(" - ?(");
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.NETWORK_EQUIPMENT)),
                AssetConstants.NETWORK_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.SECURITY_EQUIPMENT)),
                AssetConstants.SECURITY_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.SERVER_EQUIPMENT)),
                AssetConstants.SERVER_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.STORAGE_EQUIPMENT)),
                AssetConstants.STORAGE_EQUIPMENT);
        generateSheet(//from   w ww  . j a  v a 2 s .  c o  m
                wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.INFRASTRUCTURE_EQUIPMENT)),
                AssetConstants.INFRASTRUCTURE_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.TERMINATOR_EQUIPMENT)),
                AssetConstants.TERMINATOR_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.MOBILE_EQUIPMENT)),
                AssetConstants.MOBILE_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.PRINTER_EQUIPMENT)),
                AssetConstants.PRINTER_EQUIPMENT);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.OTHER_EQUIPMENT)),
                AssetConstants.OTHER_EQUIPMENT);
    } else if ("_soft".equals(type)) {
        fn.append(" - ?(");
        generateSheet(
                wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.OPERATING_SYSTEM_SOFTWARE)),
                AssetConstants.OPERATING_SYSTEM_SOFTWARE);
        generateSheet(
                wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.DATABASE_SYSTEM_SOFTWARE)),
                AssetConstants.DATABASE_SYSTEM_SOFTWARE);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.MIDDLEWARE_SOFTWARE)),
                AssetConstants.MIDDLEWARE_SOFTWARE);
        generateSheet(
                wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.STORAGE_SYSTEM_SOFTWARE)),
                AssetConstants.STORAGE_SYSTEM_SOFTWARE);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.SECURITY_SOFTWARE)),
                AssetConstants.SECURITY_SOFTWARE);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.OFFICE_SOFTWARE)),
                AssetConstants.OFFICE_SOFTWARE);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.APPLICATION_SOFTWARE)),
                AssetConstants.APPLICATION_SOFTWARE);
        generateSheet(wb.createSheet(AssetConstants.getAssetCatalogName(AssetConstants.OTHER_SOFTWARE)),
                AssetConstants.OTHER_SOFTWARE);
    } else {
        fn.append(" - IT?(");
        generateSheet(wb.createSheet(AssetConstants.getAssetTypeName(AssetConstants.HARDWARE_ASSET)),
                AssetConstants.HARDWARE_ASSET);
        generateSheet(wb.createSheet(AssetConstants.getAssetTypeName(AssetConstants.SOFTWARE_ASSET)),
                AssetConstants.SOFTWARE_ASSET);
    }
    fn.append((new SimpleDateFormat("yyyyMMdd")).format(new Date())).append(").xlsx");
    if (isIE()) {
        filename = URLEncoder.encode(fn.toString(), "UTF-8").replaceAll("\\+", "%20");
    } else {
        filename = new String(fn.toString().getBytes("UTF-8"), "iso8859-1");
    }
    resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    resp.setHeader("Content-disposition", "attachment; filename=" + filename);
    BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream(), 4096);
    wb.write(out);
    wb.close();
    out.close();
}

From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.GenItunesFile.java

private void render() throws IOException {
    fos = new FileOutputStream(outFile);
    BufferedOutputStream bufout = new BufferedOutputStream(fos, 10000000);
    sout = new OutputStreamWriter(bufout);

    sout.write(getHead());//from w w  w .java 2s .  c o  m
    // genTracksForMedia();
    genAllTrack();
    sout.write(getFoot());

    sout.close();
    bufout.close();
    fos.close();
}

From source file:crush.CrushUtil.java

protected void textCrush(FileSystem fs, FileStatus[] status) throws IOException, CrushException {
    FSDataOutputStream out = fs.create(outPath);
    BufferedOutputStream bw = new java.io.BufferedOutputStream(out);
    for (FileStatus stat : status) {
        BufferedInputStream br = new BufferedInputStream(fs.open(stat.getPath()));
        byte[] buffer = new byte[2048];
        int read = -1;
        while ((read = br.read(buffer)) != -1) {
            bw.write(buffer, 0, read);/*from www. jav  a  2s.co  m*/
        }
        br.close();
    }
    bw.close();
}

From source file:com.android.tradefed.util.FileUtil.java

public static void extractGzip(File tarGzipFile, File destDir, String destName)
        throws FileNotFoundException, IOException, ArchiveException {
    GZIPInputStream zipIn = null;
    BufferedOutputStream buffOut = null;
    try {//from   w ww. j  a va2  s .  c  om
        File destUnzipFile = new File(destDir.getAbsolutePath(), destName);
        zipIn = new GZIPInputStream(new FileInputStream(tarGzipFile));
        buffOut = new BufferedOutputStream(new FileOutputStream(destUnzipFile));
        int b = 0;
        byte[] buf = new byte[8192];
        while ((b = zipIn.read(buf)) != -1) {
            buffOut.write(buf, 0, b);
        }
    } finally {
        if (zipIn != null)
            zipIn.close();
        if (buffOut != null)
            buffOut.close();
    }
}

From source file:com.awstrainers.devcourse.sdkdemos.S3Test.java

private File createTempFile() throws IOException {
    BufferedOutputStream out = null;
    try {/* www.j ava2s  .c  om*/
        File file = File.createTempFile("s3test" + UUID.randomUUID(), ".txt");

        byte[] zeroes = new byte[1024];
        out = new BufferedOutputStream(new FileOutputStream(file));
        for (int i = 0; i < 100; i++) {
            out.write(zeroes);
        }
        return file;
    } finally {
        if (out != null)
            out.close();
    }
}