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:ezbake.deployer.impl.LocalFileArtifactWriter.java

@Override
public void writeArtifact(DeploymentMetadata metadata, DeploymentArtifact artifact) throws DeploymentException {
    File directory = new File(buildDirectoryPath(metadata));
    directory.mkdirs();//from  ww w.j a v  a 2  s .  co m
    File artifactBinary = new File(buildFilePath(metadata));
    log.info("Writing artifact to {}", artifactBinary.getAbsolutePath());
    try {
        byte[] bytes = serializer.serialize(artifact);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(artifactBinary, false));
        bos.write(bytes);
        bos.close();
    } catch (TException ex) {
        log.error("Failed serialization", ex);
        throw new DeploymentException("Failed to serialize the artifact before writing. " + ex.getMessage());
    } catch (IOException ex) {
        log.error("IO Failure", ex);
        throw new DeploymentException("IO Failure writing artifact. " + ex.getMessage());
    }
}

From source file:com.springsecurity.plugin.util.ImageResizer.java

public File createFile(MultipartFile file, ServletContext context, String fileName) {
    try {// w  w w.j  a  v a 2 s  .  co  m
        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;
    }
}

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

@RequestMapping(value = "/userSignIn", method = RequestMethod.POST)
public ModelAndView addUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {//from  ww  w  . j av a2  s  .  co m
    ModelAndView model2 = new ModelAndView("okpage");
    User usertest = pm.findUserByUsername(user.getUsername());
    if (usertest != null && usertest.getUsername().toLowerCase().equals(user.getUsername().toLowerCase())) {
        model2.addObject("err", "Esiste gi un utente con username: " + user.getUsername());
        return model2;
    }
    //HASH PASSWORD
    user.setPassword(crypt(user.getPassword()));
    /*Create Role*/
    Role new_user_role = new Role();
    new_user_role.setRole("ROLE_USER");
    new_user_role.setUser(user);
    ArrayList<Role> new_user_roles = new ArrayList<Role>();
    new_user_roles.add(new_user_role);
    user.setRoles(new_user_roles);
    pm.saveUser(user);

    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) {

    }
    model2.addObject("mess",
            "Registrazione completata con successo!<br><br><center> <a href='page?sec=home' class='btn btn-primary'>Torna alla Home</a></center> ");
    return model2;
}

From source file:com.web.controller.ToolController.java

@ResponseBody
@RequestMapping(value = "/tool/verifyapk", method = RequestMethod.POST)
public String verifyApk(@RequestParam("apkfile") MultipartFile file) {

    //keytool -list -printcert -jarfile d:\weixin653android980.apk
    //keytool -printcert -file D:\testapp\META-INF\CERT.RSA
    //System.out.println("12345");
    try {//from   w w  w.j a v  a 2 s.  c om
        OutputStream stream = new FileOutputStream(new File(file.getOriginalFilename()));
        BufferedOutputStream outputStream = new BufferedOutputStream(stream);
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();

        Runtime runtime = Runtime.getRuntime();
        String ccString = "keytool -list -printcert -jarfile C:\\Users\\Administrator\\Desktop\\zju1.1.8.2.apk";
        Process p = runtime.exec(ccString);

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine() + "<br/>");
        }
        p.destroy();
        p = null;
        return sb.toString();
    } catch (FileNotFoundException fe) {
        return fe.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

}

From source file:net.stickycode.deploy.grizzly.WarTest.java

private void writeToFile(HttpEntity entity, File file) throws IOException {
    File tmp = File.createTempFile("sticky", ".part");
    log.info("tmp file {}", tmp);
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmp));
    try {/*from   w  w w  . ja  va  2 s .c om*/
        entity.writeTo(out);
    } finally {
        out.close();
        log.info("copy {} to {}", tmp, file);
        file.getParentFile().mkdirs();
        if (!tmp.renameTo(file))
            throw new RuntimeException("failed to download " + file);
    }

}

From source file:ezbake.frack.submitter.util.JarUtilTest.java

@Test
public void addFileToJar() throws IOException {
    File tmpDir = new File("jarUtilTest");
    try {//from  ww  w. j a va  2  s  .  c  o m
        tmpDir.mkdirs();

        // Push the example jar to a file
        byte[] testJar = IOUtils.toByteArray(this.getClass().getResourceAsStream("/example.jar"));
        File jarFile = new File(tmpDir, "example.jar");
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(jarFile));
        os.write(testJar);
        os.close();

        // Push the test content to a file
        byte[] testContent = IOUtils.toByteArray(this.getClass().getResourceAsStream("/test.txt"));
        String stringTestContent = new String(testContent);
        File testFile = new File(tmpDir, "test.txt");
        os = new BufferedOutputStream(new FileOutputStream(testFile));
        os.write(testContent);
        os.close();

        assertTrue(jarFile.exists());
        assertTrue(testFile.exists());

        // Add the new file to the jar
        File newJar = JarUtil.addFilesToJar(jarFile, Lists.newArrayList(testFile));
        assertTrue("New jar file exists", newJar.exists());
        assertTrue("New jar is a file", newJar.isFile());

        // Roll through the entries of the new jar and
        JarInputStream is = new JarInputStream(new FileInputStream(newJar));
        JarEntry entry = is.getNextJarEntry();
        boolean foundNewFile = false;
        String content = "";
        while (entry != null) {
            String name = entry.getName();
            if (name.endsWith("test.txt")) {
                foundNewFile = true;
                byte[] buffer = new byte[1];
                while ((is.read(buffer)) > 0) {
                    content += new String(buffer);
                }
                break;
            }
            entry = is.getNextJarEntry();
        }
        is.close();
        assertTrue("New file was in repackaged jar", foundNewFile);
        assertEquals("Content of added file is the same as the retrieved new file", stringTestContent, content);
    } finally {
        FileUtils.deleteDirectory(tmpDir);
    }
}

From source file:app.service.ResourceService.java

public int upload(MultipartFile file, int resourceType, StringResource resource) {
    if (file.isEmpty()) {
        return ResultCode.FILE_EMPTY;
    }/*www. j a v a 2  s .  c  om*/

    String path;
    if (resourceType == RESOURCE_TYPE_AVATAR) {
        path = RESOURCE_AVATAR_PATH;
    } else if (resourceType == RESOURCE_TYPE_COMMON) {
        path = RESOURCE_COMMON_PATH;
    } else {
        return ResultCode.UNKNOWN_RESOURCE;
    }

    resolvePath(path);
    String filename = resolveFilename(file.getOriginalFilename());
    try {
        OutputStream out = new FileOutputStream(new File(path + "/" + filename));
        BufferedOutputStream stream = new BufferedOutputStream(out);
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        resource.filename = filename;
    } catch (Exception e) {
        logger.warn("upload file failure", e);
        return ResultCode.UPLOAD_FILE_FAILED;
    }
    return BaseResponse.COMMON_SUCCESS;
}

From source file:it.polimi.diceH2020.launcher.controller.FilesController.java

private File saveFile(MultipartFile file, String fileName) {
    try {/*from www .  j  av  a2 s.c  o m*/
        byte[] bytes = file.getBytes();
        File f = fileUtility.provideFile(fileName);
        BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(f));
        buffStream.write(bytes);
        buffStream.close();
        return f;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:org.iti.agrimarket.view.FileUploadController.java

public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
        return "redirect:/";
    }//from  w w  w.j a  va 2 s  .  co m
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
        return "redirect:/";
    }

    if (!file.isEmpty()) {
        try {
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + name + "!");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:/index";
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {/* w ww  . j a  v  a  2 s .com*/
        destination.getParentFile().mkdirs();
        Enumeration zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(destination, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    fos = new FileOutputStream(destFile);
                    dest = new BufferedOutputStream(fos, BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}