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:ai.api.RequestTask.java

@Override
protected String doInBackground(final String... params) {
    final String payload = params[0];
    if (TextUtils.isEmpty(payload)) {
        throw new IllegalArgumentException("payload argument should not be empty");
    }/*from ww w.ja va  2  s  . c  om*/

    String response = null;
    HttpURLConnection connection = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);

        connection.connect();

        final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(payload, outputStream, Charsets.UTF_8);
        outputStream.close();

        final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
        response = IOUtils.toString(inputStream, Charsets.UTF_8);
        inputStream.close();

        return response;

    } catch (final IOException e) {
        Log.e(TAG,
                "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.",
                e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;
}

From source file:backend.translator.GTranslator.java

private File downloadFile(String url) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    request.addHeader("User-Agent", "Mozilla/5.0");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    BufferedInputStream bis = new BufferedInputStream(entity.getContent());
    File f = new File(R.TRANS_RESULT_PATH);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
    int inByte;/*from  w  ww .  ja v  a 2s . c o  m*/
    while ((inByte = bis.read()) != -1)
        bos.write(inByte);

    bis.close();
    bos.close();
    return f;
}

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

@RequestMapping(value = "userEditProfile", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ModelAndView updateUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {/*from  w  w w.j av  a  2  s  .  c o  m*/
    ModelAndView model = new ModelAndView("userInfo");
    User olduser = pm.findUserByUsername(user.getUsername());
    user.setId(olduser.getId());

    if (user.getPassword() == null || user.getPassword().equals("")) {
        user.setPassword(olduser.getPassword());
    } else {
        user.setPassword(crypt(user.getPassword()));
    }

    pm.saveUser(user);

    if (avatar.getSize() > 0) {

        User user2 = pm.findUserByUsername(user.getUsername());
        MultipartFile file = avatar;

        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 + "user" + File.separator + "img"
                    + File.separator + user2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "avatar.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {

        }

    }
    model.addObject("user", user);
    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
            + File.separator + user.getId() + File.separator + "avatar.jpg");
    if (dir.exists()) {
        model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
    } else {
        model.addObject("avatar", "./dist/img/default_avatar.png");
    }
    return model;
}

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 w ww  . ja va  2s .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:dk.deck.resolver.util.ZipUtils.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        return;/*from w w  w  .  j  a  va 2  s .  c  o  m*/
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    // log.debug("Extracting: " + entry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:de.petermoesenthin.alarming.util.FileUtil.java

/**
 * Copies a file to the Alarming directory in the external storage
 *
 * @param context Application context/*from w ww . j  av a2  s .com*/
 * @param uri     Uri of file to copy
 */
public static void saveFileToExtAppStorage(final Context context, final Uri uri,
        final OnCopyFinishedListener op) {
    final File applicationDirectory = getApplicationDirectory();
    if (!applicationDirectory.exists()) {
        applicationDirectory.mkdirs();
    }
    File noMedia = new File(applicationDirectory.getPath() + File.separatorChar + ".nomedia");
    if (!noMedia.exists()) {
        try {
            noMedia.createNewFile();
            Log.e(DEBUG_TAG, "Created .nomedia file in: " + noMedia.getAbsolutePath());
        } catch (IOException e) {
            Log.e(DEBUG_TAG, "Unable to create .nomedia file", e);
        }
    }

    String fileName = getFilenameFromUriNoSpace(uri);
    final File destinationFile = new File(applicationDirectory.getPath() + File.separatorChar + fileName);

    Log.d(DEBUG_TAG, "Source file name: " + fileName);
    Log.d(DEBUG_TAG, "Source file uri: " + uri.toString());
    Log.d(DEBUG_TAG, "Destination file: " + destinationFile.getPath());

    Thread copyThread = new Thread(new Runnable() {
        @Override
        public void run() {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            if (isExternalStorageWritable()) {
                try {
                    InputStream uriStream = context.getContentResolver().openInputStream(uri);
                    bis = new BufferedInputStream(uriStream);
                    bos = new BufferedOutputStream(new FileOutputStream(destinationFile.getPath(), false));
                    byte[] buf = new byte[1024];
                    while (bis.read(buf) != -1) {
                        bos.write(buf);
                    }
                } catch (IOException e) {
                    Log.e(DEBUG_TAG, "Unable to copy file from URI", e);

                } finally {
                    try {
                        if (bis != null)
                            bis.close();
                        if (bos != null)
                            bos.close();
                    } catch (IOException e) {
                        Log.e(DEBUG_TAG, "Unable to close buffers", e);
                    }
                }
            }
            if (op != null) {
                op.onOperationFinished();
            }
        }
    });
    copyThread.start();
}

From source file:com.kalai.controller.FileUploadController.java

@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
public @ResponseBody String fileuploadstore(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file, ModelMap map) {
    if (!file.isEmpty()) {
        try {//w w  w  .j  a  va2s . c o m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded Successfully" + name);

        } catch (Exception e) {
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded UnSuccessfully" + name);
        }
    } else {
        map.addAttribute("Status", "uploaded  is Empty" + name);
    }
    return "fileupload";
}

From source file:com.metamolecular.pubcouch.test.SnapshotTest.java

private byte[] zipStringToBytes(String input) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
    bufos.write(input.getBytes("UTF-8"));
    bufos.close();
    byte[] retval = bos.toByteArray();
    bos.close();//from ww w. ja  va 2s . c om
    return retval;
}

From source file:com.sun.socialsite.util.Utilities.java

/**
 * Utility method to copy an input stream to an output stream.
 * Wraps both streams in buffers. Ensures right numbers of bytes copied.
 *///  w  w w .jav  a2 s .  c  om
public static void copyInputToOutput(InputStream input, OutputStream output, long byteCount)
        throws IOException {
    int bytes;
    long length;

    BufferedInputStream in = new BufferedInputStream(input);
    BufferedOutputStream out = new BufferedOutputStream(output);

    byte[] buffer;
    buffer = new byte[8192];

    for (length = byteCount; length > 0;) {
        bytes = (int) (length > 8192 ? 8192 : length);

        try {
            bytes = in.read(buffer, 0, bytes);
        } catch (IOException ex) {
            try {
                in.close();
                out.close();
            } catch (IOException ex1) {
            }
            throw new IOException("Reading input stream, " + ex.getMessage());
        }

        if (bytes < 0)
            break;

        length -= bytes;

        try {
            out.write(buffer, 0, bytes);
        } catch (IOException ex) {
            try {
                in.close();
                out.close();
            } catch (IOException ex1) {
            }
            throw new IOException("Writing output stream, " + ex.getMessage());
        }
    }

    try {
        in.close();
        out.close();
    } catch (IOException ex) {
        throw new IOException("Closing file streams, " + ex.getMessage());
    }
}

From source file:equipeDFK.sistemaX.controller.ControllerAgenda.java

/**
 * Mtodo que recebe uma requisio para importar os feriados,
 * ento ler o arquivo CSV e depois persistir os dados no banco
 * @param arquivoCSV//w  w w  .  java 2s. c  o m
 * @param sobrescrever
 * @param req
 * @return String
 * @throws SQLException 
 */
@RequestMapping("openCSV")
public String OpenCSV(MultipartFile arquivoCSV, boolean sobrescrever, HttpServletRequest req)
        throws SQLException {
    GerenciadorDeFeriado gf = new GerenciadorDeFeriado();
    if (!arquivoCSV.isEmpty()) {
        try {
            byte[] b = arquivoCSV.getBytes();
            String caminho = req.getServletContext().getRealPath("/") + arquivoCSV.getOriginalFilename();
            System.out.println(caminho);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(caminho)));
            stream.write(b);
            stream.close();
            OpenCSV opencsv = new OpenCSV();
            if (sobrescrever) {

            } else {

            }
            gf.importaferiado(opencsv.lerCSV(new File(caminho)), sobrescrever);
            List eventos = gf.listar();
            eventos.stream().forEach((evento) -> {
                System.out.println(evento);
            });
            req.getSession().setAttribute("feriados", eventos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return "managerHoliday";
}