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:edu.ur.util.FileUtil.java

/**
 * Create a file in the specified directory with the
 * specified name and place in it the specified contents.
 *
 * @param directory - directory in which to create the file
 * @param fileName - name of the file to create
 * @param contents - Simple string to create the file
 *///from w ww.  ja v  a2  s .  co m
public File creatFile(File directory, String fileName, String contents) {
    File f = new File(directory.getAbsolutePath() + IOUtils.DIR_SEPARATOR + fileName);

    // create the file
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    try {

        f.createNewFile();
        fos = new FileOutputStream(f);
        bos = new BufferedOutputStream(fos);

        bos.write(contents.getBytes());
        bos.flush();
        bos.close();
        fos.close();
    } catch (Exception e) {
        if (bos != null) {
            try {
                bos.close();
            } catch (Exception ec) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ec) {
            }
        }
        throw new RuntimeException(e);
    }

    return f;
}

From source file:com.card.loop.xyz.controller.LearningElementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("title") String title, @RequestParam("author") String author,
        @RequestParam("subject") String subject, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file, @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {//from   w w  w  .  j  a  va  2  s.  c o m
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.USER_VARIABLE + AppConfig.LE_FILE_PATH + file.getOriginalFilename());

            if (!fil.getParentFile().exists()) {
                fil.getParentFile().mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningElement le = new LearningElement();
            le.setTitle(title);
            le.setUploadedBy(author);
            le.setDescription(description);
            le.setDownloads(0);
            le.setStatus(1);
            le.setRating(1);
            le.setUploadDate(new Date());
            le.setSubject(subject);
            le.setFilePath(AppConfig.LE_FILE_PATH);
            le.setFilename(file.getOriginalFilename());
            le.setContentType(file.getOriginalFilename().split("\\.")[1]);
            dao.addLearningElement(le);

            System.out.println("UPLOAD LE FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }
    return new ModelAndView("developer-le-loop-redirect");
}

From source file:fr.shywim.antoinedaniel.sync.AppState.java

/**
 * Save the AppState to a file./* w ww  .  j ava2  s  .  c  o m*/
 *
 * @param context a context.
 */
public void save(Context context) {
    if (changed) {
        File privDir = context.getFilesDir();
        File appState = new File(privDir, FILE_NAME);

        try {
            byte[] bytes = getAsByteArray();
            if (appState.exists() || (!appState.exists() && appState.createNewFile())) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(appState));
                bos.write(bytes);
                bos.flush();
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

@RequestMapping(value = "uploadMultipleFiles", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("files") MultipartFile files[]) {
    try {/* w  ww.j  a v a 2s. c  om*/
        String filepath = "D:/spring_file_upload/";
        StringBuffer result = new StringBuffer();
        byte[] bytes = null;
        result.append("Uploading of files(s)");
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isEmpty()) {
                bytes = files[i].getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(filepath + files[i].getOriginalFilename())));
                stream.write(bytes);
                stream.close();
                result.append(files[i].getOriginalFilename() + "OK.");
            } else {
                result.append(files[i].getOriginalFilename() + "Failed.");
            }
        }
        return result.toString();
    } catch (Exception e) {
        return e.getMessage();

    }
}

From source file:org.caboclo.clients.ApiClient.java

protected void downloadURL(String url, File file, Map<String, String> headers)
        throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    for (String key : headers.keySet()) {
        String value = headers.get(key);

        httpget.setHeader(key, value);/*from  w  ww.  j av  a  2s.co m*/
    }

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (IllegalStateException ex) {
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:eu.mrbussy.security.crypto.pgp.PGPDecryptor.java

public void decryptFile(InputStream in, OutputStream out) throws Exception {
    BufferedOutputStream bOut = new BufferedOutputStream(out);
    InputStream unc = decryptFile(in);
    int ch;/* w  ww  .jav a 2 s .  c  om*/
    while ((ch = unc.read()) >= 0) {
        bOut.write(ch);
    }
    bOut.close();
}

From source file:hu.bme.iit.quiz.service.QuizServiceImpl.java

@Override
public String validateAndCreateQuizForUserFromFile(MultipartFile file, String quizName, String loginName) {
    String originalFileName = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {/*from   w  w  w.j  a v  a  2  s . c  om*/
            byte[] bytes = file.getBytes();

            //Only XML files, no mime check, basic check
            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return "You failed to upload " + originalFileName + " because it's not an XML file.";
            }

            // 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();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd-HH-mm-ss");
            Date now = new Date();
            String innerFileLocation = dateFormat.format(now) + "_" + originalFileName;

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

            //Persist it in db
            Quiz quiz = new Quiz();
            quiz.setName(quizName);
            quiz.setBlobdata(bytes);
            quiz.setLocation(innerFileLocation);
            quiz.setUploaded(new Date());
            quiz.setInnerkey(UUID.randomUUID().toString());
            quiz.setOwner(userDAO.getUser(loginName));

            if (getQuizDataFromXML(quiz) != null) {
                quizDAO.addQuiz(quiz);
            } else {
                return "Invalid XML file!";
            }

            logger.info("XML file uploaded: " + originalFileName);
            return "You successfully uploaded '" + originalFileName + "'";
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return "You failed to upload " + originalFileName + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + originalFileName + " because the file was empty.";
    }
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Restore backup data/*from  w  w  w . j  ava2s  .  c o  m*/
 *
 * @param fileData - json file with restore data
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/api/backup", method = RequestMethod.POST)
public @ResponseBody Backup processBackup(@RequestParam("fileData") MultipartFile fileData) throws Exception {
    // Method taken from: http://spring.io/guides/gs/uploading-files/
    if (!fileData.isEmpty()) {
        try {
            byte[] bytes = fileData.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("backup-uploaded.json")));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
        }
    }
    File f = new File("backup-uploaded.json");
    BackupService.getInstance().restoreBackupData(new FileInputStream(f));
    return BackupService.getInstance().getBackupData();
}

From source file:org.broadleafcommerce.admin.util.controllers.FileUploadController.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, IOException {

    // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFile();
    if (file == null) {
        // hmm, that's strange, the user did not upload anything
    }/*from  w  w  w  . j a va2  s .  c o m*/

    try {
        String basepath = request.getPathTranslated().substring(0,
                request.getPathTranslated().indexOf(File.separator + "upload"));
        String absoluteFilename = basepath + File.separator + bean.getDirectory() + File.separator
                + file.getOriginalFilename();
        FileSystemResource fileResource = new FileSystemResource(absoluteFilename);

        checkDirectory(basepath + File.separator + bean.getDirectory());

        backupExistingFile(fileResource, basepath + bean.getDirectory());

        FileOutputStream fout = new FileOutputStream(new FileSystemResource(
                basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename())
                        .getFile());
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
        int x;
        while ((x = bin.read()) != -1) {
            bout.write(x);
        }
        bout.flush();
        bout.close();
        bin.close();
        return super.onSubmit(request, response, command, errors);
    } catch (Exception e) {
        //Exception occured;
        e.printStackTrace();
        throw new RuntimeException(e);
        // return null;                
    }
}

From source file:com.wipro.ats.bdre.md.rest.TDUploaderAPI.java

@RequestMapping(value = "/uploadtr/{processIdValue}", method = RequestMethod.POST)
@ResponseBody/*from   w  w  w .ja v  a2s.co  m*/
public RestWrapper uploadInTeradata(@PathVariable("processIdValue") Integer processIdValue,
        @RequestParam("file") MultipartFile file, Principal principal) {

    if (!file.isEmpty()) {
        try {

            String uploadedFilesDirectory = MDConfig.getProperty(UPLOADBASEDIRECTORY);
            String name = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String monitorPath = null;
            LOGGER.info("processIDvalue is " + processIdValue);
            com.wipro.ats.bdre.md.dao.jpa.Process process = processDAO.get(processIdValue);
            LOGGER.info("Process fetched = " + process.getProcessId());
            List<Properties> propertiesList = propertiesDAO.getByProcessId(process);
            LOGGER.info("No.of Properties fetched= " + propertiesList.size());
            for (Properties property : propertiesList) {
                LOGGER.debug(
                        "property fetched is " + property.getId().getPropKey() + " " + property.getPropValue());
                if ("monitored-dir-name".equals(property.getId().getPropKey())) {
                    monitorPath = property.getPropValue();
                }
            }
            String uploadLocation = monitorPath;
            LOGGER.info("Upload location: " + uploadLocation);
            File fileDir = new File(uploadLocation);
            fileDir.mkdirs();
            File fileToBeSaved = new File(uploadLocation + "/" + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToBeSaved));
            stream.write(bytes);
            stream.close();
            LOGGER.debug("Uploaded file: " + fileToBeSaved);

            //Populating Uploaded file bean to return in RestWrapper
            UploadedFile uploadedFile = new UploadedFile();
            uploadedFile.setParentProcessId(processIdValue);
            // uploadedFile.setSubDir(subDir);
            uploadedFile.setFileName(name);
            uploadedFile.setFileSize(fileToBeSaved.length());
            LOGGER.debug("The UploadedFile bean:" + uploadedFile);
            LOGGER.info("File uploaded : " + uploadedFile + " uploaded by User:" + principal.getName());

            return new RestWrapper(uploadedFile, RestWrapper.OK);
        } catch (Exception e) {
            LOGGER.error(e);
            return new RestWrapper(e.getMessage(), RestWrapper.ERROR);
        }
    } else {
        return new RestWrapper("You failed to upload because the file was empty.", RestWrapper.ERROR);

    }
}