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:action.ImageResult.java

public void execute(ActionInvocation invocation) throws IOException {
    ImageAction action = (ImageAction) invocation.getAction();
    HttpServletResponse response = ServletActionContext.getResponse();
    ServletOutputStream sos = response.getOutputStream();
    BufferedOutputStream output = null;
    byte[] imgBytes = action.getCustomImageInBytes();
    System.out.println("imgBytes--->" + imgBytes.toString());

    response.reset();/*ww  w  .  j a  v a2 s . co m*/
    response.setBufferSize(10240);
    response.setContentType("image/png");
    response.setContentLength(action.getCustomImageInBytes().length);
    response.setHeader("Content-Disposition", "inline; filename=\"sss\"");
    //response.getOutputStream().write(action.getCustomImageInBytes());
    // response.getOutputStream().flush();
    try {
        output = new BufferedOutputStream(response.getOutputStream(), 10240);
        output.write(imgBytes);
    } finally {
        // Gently close streams.
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.wabacus.WabacusFacade.java

public static void downloadFile(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/x-msdownload;");
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    String realfilepath = null;/*from  w  ww .j  a  v  a  2s  .  co m*/
    try {
        bos = new BufferedOutputStream(response.getOutputStream());
        String serverfilename = request.getParameter("serverfilename");
        String serverfilepath = request.getParameter("serverfilepath");
        String newfilename = request.getParameter("newfilename");
        if (serverfilename == null || serverfilename.trim().equals("")) {
            bos.write("????".getBytes());
            return;
        }
        if (serverfilename.indexOf("/") >= 0 || serverfilename.indexOf("\\") >= 0) {
            bos.write("?????".getBytes());
            return;
        }
        if (serverfilepath == null || serverfilepath.trim().equals("")) {
            bos.write("??".getBytes());
            return;
        }
        if (newfilename == null || newfilename.trim().equals(""))
            newfilename = serverfilename;
        newfilename = WabacusAssistant.getInstance().encodeAttachFilename(request, newfilename);
        response.setHeader("Content-disposition", "attachment;filename=" + newfilename);
        //response.setHeader("Content-disposition","inline;filename="+newfilename);
        String realserverfilepath = null;
        if (Tools.isDefineKey("$", serverfilepath)) {
            realserverfilepath = Config.getInstance().getResourceString(null, null, serverfilepath, true);
        } else {
            realserverfilepath = WabacusUtils.decodeFilePath(serverfilepath);
        }
        if (realserverfilepath == null || realserverfilepath.trim().equals("")) {
            bos.write(("?" + serverfilepath + "??").getBytes());
        }
        realserverfilepath = WabacusAssistant.getInstance().parseConfigPathToRealPath(realserverfilepath,
                Config.webroot_abspath);
        if (Tools.isDefineKey("classpath", realserverfilepath)) {
            realserverfilepath = Tools.getRealKeyByDefine("classpath", realserverfilepath);
            realserverfilepath = Tools.replaceAll(realserverfilepath + "/" + serverfilename, "//", "/").trim();
            while (realserverfilepath.startsWith("/"))
                realserverfilepath = realserverfilepath.substring(1);//???ClassLoader?Class?/
            bis = new BufferedInputStream(
                    ConfigLoadManager.currentDynClassLoader.getResourceAsStream(realserverfilepath));
            response.setContentLength(bis.available());
        } else {
            File downloadFileObj = new File(FilePathAssistant.getInstance()
                    .standardFilePath(realserverfilepath + File.separator + serverfilename));
            if (!downloadFileObj.exists() || downloadFileObj.isDirectory()) {
                bos.write(("?" + serverfilename).getBytes());
                return;
            }
            //response.setHeader("Content-Length", String.valueOf(downloadFileObj.length()));
            bis = new BufferedInputStream(new FileInputStream(downloadFileObj));
        }
        byte[] buff = new byte[1024];
        int bytesRead;
        while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (IOException e) {
        throw new WabacusRuntimeException("" + realfilepath + "", e);
    } finally {
        try {
            if (bis != null)
                bis.close();
        } catch (IOException e) {
            log.warn("" + realfilepath + "?", e);
        }
        try {
            if (bos != null)
                bos.close();
        } catch (IOException e) {
            log.warn("" + realfilepath + "?", e);
        }
    }
}

From source file:com.nokia.carbide.installpackages.InstallPackages.java

private URL getAvailablePackagesURL() throws Exception {
    URL url = null;/*from  ww w  .  j a  v a  2  s.  c o  m*/

    // see if the file is local (Ed's hack for testing...)
    String masterFilePathStr = getMasterFilePath();
    url = new URL(masterFilePathStr);
    if (url.getProtocol().equals("file")) {
        return url;
    }

    // else, read the file to a local temporary location
    GetMethod getMethod = new GetMethod(masterFilePathStr);
    HttpClient client = new HttpClient();
    setProxyData(client, getMethod);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    int serverStatus = 0;
    byte[] responseBody;
    try {
        serverStatus = client.executeMethod(getMethod);
        responseBody = getMethod.getResponseBody();
    } catch (Exception e) {
        // could be HttpException or IOException
        throw new Exception(e);
    } finally {
        getMethod.releaseConnection();
    }

    // HTTP status codes: 2xx = Success
    if (serverStatus >= 200 && serverStatus < 300) {
        File tempDir = FileUtils.getTemporaryDirectory();
        IPath path = new Path(tempDir.getAbsolutePath());
        IPath masterFilePath = path.append(getMasterFileName());
        File masterFile = masterFilePath.toFile();
        if (masterFile.exists())
            masterFile.delete();
        FileOutputStream fos = new FileOutputStream(masterFile);
        BufferedOutputStream out = new BufferedOutputStream(fos);
        ByteArrayInputStream in = new ByteArrayInputStream(responseBody);
        boolean foundOpenBrace = false;
        int c;
        while ((c = in.read()) != -1) {
            if (c == '<')
                foundOpenBrace = true;
            if (foundOpenBrace)
                out.write(c);
        }
        out.close();
        in.close();
        url = masterFile.toURI().toURL();

        return url;
    }
    return null;
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void putObject(String bucket, String object, byte[] base64Data, boolean append) throws IOException {
    File objectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + object);
    if (!objectFile.exists()) {
        objectFile.createNewFile();//from   ww  w. ja v a2 s. c om
    }
    BufferedOutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(new FileOutputStream(objectFile, append));
        outputStream.write(base64Data);
    } finally {
        if (outputStream != null)
            outputStream.close();
    }
}

From source file:energy.usef.environment.tool.GenerateDomains.java

private void generateDataSources() throws IOException {
    for (String nodeName : environmentConfig.getNodeNames()) {
        NodeConfig nodeConfig = environmentConfig.getNodeConfig(nodeName);

        StringBuffer datasources = new StringBuffer("");

        if (environmentConfig.isDatabasePerParticipant()) {
            List<RoleConfig> domains = environmentConfig.getDomainRoleConfig(nodeConfig);

            for (RoleConfig roleConfig : domains) {
                String dbFilename = ToolConfig.getUsefEnvironmentDomainDataFolder(nodeName) + File.separator
                        + roleConfig.getDomain();
                datasources.append(getDataSource(roleConfig.getUniqueDatasourceName(),
                        getDbUrl(dbFilename).replace("\\", "/")));
            }//  w  w  w  . j a v  a  2 s.  c  o  m
        } else {
            String dbFilename = ToolConfig.getUsefEnvironmentDomainDataFolder(nodeName) + File.separator
                    + "usef_db";
            datasources.append(getDataSource("USEF_DS", getDbUrl(dbFilename).replace("\\", "/")));
        }

        String standaloneXml = ToolConfig.getUsefEnvironmentDomainConfigurationFolder(nodeName) + File.separator
                + ToolConfig.STANDALONE_XML;

        List<String> config = new ArrayList<>();
        List<String> templateConfig = FileUtil.readLines(
                ToolConfig.getUsefEnvironmentTemplateFolder() + File.separator + ToolConfig.STANDALONE_XML);

        for (String line : templateConfig) {
            if ("USEF_DATASOURCES".equalsIgnoreCase(line)) {
                config.add(datasources.toString());
            } else {
                config.add(line);
            }
        }

        BufferedOutputStream bout = null;
        try {
            bout = new BufferedOutputStream(new FileOutputStream(standaloneXml));

            for (String line : config) {
                line += System.getProperty("line.separator");
                bout.write(line.getBytes());
            }
        } catch (IOException e) {
        } finally {
            if (bout != null) {
                try {
                    bout.close();
                } catch (Exception e) {
                }
            }
        }
    }
}

From source file:controller.CommercialController.java

@RequestMapping("regub/commercial/contrats/comajoutcontrat")
public String ajoutcontratAction(HttpServletRequest request, HttpSession session, Model model,
        @RequestParam("file") MultipartFile file) throws ParseException, InterruptedException {

    //Pour pouvoir conserver l'Id du client pour lequel 
    //l'ajout du contrat est fait
    int id = cleclient;

    String[] choixrayon = request.getParameterValues("rayon");
    String[] choixregion = request.getParameterValues("region");
    String titrecontrat = request.getParameter("titre");
    String freqcontrat = request.getParameter("frequence");
    String durecontrat = request.getParameter("duree");
    String datedebutcontrat = request.getParameter("datedebut");
    String datefincontrat = request.getParameter("datefin");
    String daterecepcontrat = request.getParameter("datereception");
    String datevalidcontrat = request.getParameter("datevalidation");
    String tarifcontrat = request.getParameter("tarif");
    String choixstatut = request.getParameter("statut");

    Set<Region> mySetregion = tableaureg(choixregion);
    Set<Typerayon> mySettyperayon = tableauray(choixrayon);

    Client client = ClientDAO.Charge(id).get(0);
    Compte comcompt = (Compte) session.getAttribute("compteConnected");

    DateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");
    Date currentDate = new Date();
    String datecourante = dateformat.format(currentDate);

    Video vid = new Video(client, comcompt, titrecontrat, Integer.parseInt(freqcontrat),
            Integer.parseInt(durecontrat), ConvertToSqlDate(datedebutcontrat), ConvertToSqlDate(datefincontrat),
            ConvertToSqlDate(daterecepcontrat), ConvertToSqlDate(datecourante),
            Double.parseDouble(tarifcontrat), Integer.parseInt(choixstatut), mySetregion, mySettyperayon);

    int videoid = VidBDD.addComContrat(vid);// appelle de la mthode pr inserer dans la table video et recup de l'id de l'element qui a t insr

    if (!file.isEmpty()) {
        try {/*from  ww w . j  a v a2 s.c om*/
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            //System.out.println(""+rootPath+File.separator);
            //System.out.println(""+file.getOriginalFilename());

            // Create the file on server
            //file.getOriginalFilename() permet de recup le nom du fichier original selectionn
            //Mon chemein de test
            //File serverFile = new File("A:\\test"+ File.separator + 20 + ".mp4");//a marche
            //Chemin officiel du serveur
            File serverFile = new File(rootPath + File.separator + "webapps" + File.separator + "manager"
                    + File.separator + "videos" + File.separator + videoid + ".mp4");
            System.out.println("" + serverFile);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("You failed to upload ");
    }

    //return "redirect:/regub/commercial";
    return "redirect:/regub/commercial/contrats/" + vid.getClient().getIdClient();

}

From source file:com.tresys.jalop.utils.jnltest.SubscriberImpl.java

/**
 * Write status information about a record out to disk.
 * @param file The {@link File} object to write to
 * @param toWrite The {@link JSONObject} that will be written to the file
 * @return <code>true</code> If the data was successfully written out.
 *         <code>false</code> otherwise.
 *///from w  w w  .ja  v  a 2 s  .c  om
final boolean dumpStatus(final File file, final JSONObject toWrite) {
    BufferedOutputStream w;
    try {
        w = new BufferedOutputStream(new FileOutputStream(file));
        w.write(toWrite.toJSONString().getBytes("utf-8"));
        w.close();
    } catch (final FileNotFoundException e) {
        LOGGER.error("Failed to open file (" + file.getPath() + ") for writing:" + e.getMessage());
        return false;
    } catch (final UnsupportedEncodingException e) {
        SubscriberImpl.LOGGER.error("cannot find UTF-8 encoder?");
        return false;
    } catch (final IOException e) {
        LOGGER.error("failed to write to the file (" + file.getPath() + "), aborting");
        return false;
    }
    return true;
}

From source file:PNGDecoder.java

/** main encoding method (stays blocked till encoding is finished).
 * @param image BufferedImage to encode//from  w  w w  .  ja va 2s  . c o m
 * @throws IOException IOException
 */
public void encode(BufferedImage image) throws IOException {
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    final byte id[] = { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 };
    write(id);
    crc.reset();
    write("IHDR".getBytes());
    write(width);
    write(height);
    byte head[] = null;
    switch (mode) {
    case BW_MODE:
        head = new byte[] { 1, 0, 0, 0, 0 };
        break;
    case GREYSCALE_MODE:
        head = new byte[] { 8, 0, 0, 0, 0 };
        break;
    case COLOR_MODE:
        head = new byte[] { 8, 2, 0, 0, 0 };
        break;
    }
    write(head);
    write((int) crc.getValue());
    ByteArrayOutputStream compressed = new ByteArrayOutputStream(65536);
    BufferedOutputStream bos = new BufferedOutputStream(new DeflaterOutputStream(compressed, new Deflater(9)));
    int pixel;
    int color;
    int colorset;
    switch (mode) {
    case BW_MODE:
        int rest = width % 8;
        int bytes = width / 8;
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < bytes; x++) {
                colorset = 0;
                for (int sh = 0; sh < 8; sh++) {
                    pixel = image.getRGB(x * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                bos.write((byte) colorset);
            }
            if (rest > 0) {
                colorset = 0;
                for (int sh = 0; sh < width % 8; sh++) {
                    pixel = image.getRGB(bytes * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                colorset <<= 8 - rest;
                bos.write((byte) colorset);
            }
        }
        break;
    case GREYSCALE_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                color = ((pixel >> 16) & 0xff);
                color += ((pixel >> 8) & 0xff);
                color += (pixel & 0xff);
                bos.write((byte) (color / 3));
            }
        }
        break;
    case COLOR_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                bos.write((byte) ((pixel >> 16) & 0xff));
                bos.write((byte) ((pixel >> 8) & 0xff));
                bos.write((byte) (pixel & 0xff));
            }
        }
        break;
    }
    bos.close();
    write(compressed.size());
    crc.reset();
    write("IDAT".getBytes());
    write(compressed.toByteArray());
    write((int) crc.getValue());
    write(0);
    crc.reset();
    write("IEND".getBytes());
    write((int) crc.getValue());
    out.close();
}

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

@Override
public void getFile(File file, String child) throws IOException {
    String source = getFileID(child);
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(source);
    HttpResponse response = httpclient.execute(httpget);
    //System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {// www  .  j  ava 2s  .  co  m
            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:com.izforge.izpack.event.AntActionInstallerListener.java

private File getBuildFileFromResource(SpecHelper spec, IXMLElement el) {
    File buildResourceFile = null;

    // See if the build file is a resource
    String attr = el.getAttribute("buildresource");
    if (null != attr) {
        // Get the resource
        BufferedInputStream bis = new BufferedInputStream(spec.getResource(attr));
        BufferedOutputStream bos = null;
        try {//from  w  w w.ja v a  2s .  co m
            // Write the resource to a temporary file
            File tempFile = File.createTempFile("resource_" + attr, ".xml");
            tempFile.deleteOnExit();
            bos = new BufferedOutputStream(new FileOutputStream(tempFile));
            int aByte;
            while (-1 != (aByte = bis.read())) {
                bos.write(aByte);
            }
            buildResourceFile = tempFile;
        } catch (IOException x) {
            throw new InstallerException(
                    "I/O error during writing resource " + attr + " to a temporary buildfile", x);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(bis);
        }
    }
    return buildResourceFile;
}