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:com.fluidops.iwb.deepzoom.ImageLoader.java

/**
 * Loads an image from a URL to a local file
 * @param url - The URL from which to obtain the image
 * @param file - The file to store the image to
 * @return/* w  w  w . j  a v a  2 s.c  om*/
 */

public boolean loadImage(String url, File file) {
    URL u;
    InputStream is = null;
    BufferedInputStream dis = null;
    int b;
    try {
        try {
            u = new URL(url);
        } catch (MalformedURLException e) {
            // this is the case if we work with relative URLs (in eCM)
            // just prepend the base URL#
            u = new URL(serverURL + url);
        }

        try {
            is = u.openStream();
        } catch (IOException e) {
            System.out.println("File could not be found: " + url);

            // quick fix: 200px-Image n/a, try smaller pic (for Wikipedia images)
            url = url.replace("200px", "94px");
            u = new URL(url);
            try {
                is = u.openStream();
            } catch (IOException e2) {
                System.out.println("also smaller image not available");
                return false;
            }
        }
        dis = new BufferedInputStream(is);
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            while ((b = dis.read()) != -1) {
                out.write(b);
            }
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (MalformedURLException mue) {
        logger.error(mue.getMessage(), mue);
        return false;

    } catch (IOException ioe) {
        logger.error(ioe.getMessage(), ioe);
        return false;
    } finally {
        IOUtils.closeQuietly(dis);
    }
    return true;
}

From source file:es.mityc.firmaJava.configuracion.Configuracion.java

/**
  * Este mtodo guarda la configuracin en el fichero SignXML.properties
  * @throws IOException /*from w w  w .  j a v  a  2 s .  co m*/
  */
public void guardarConfiguracion() throws IOException {
    StringBuffer paraGrabar = new StringBuffer();
    String linea;

    // La configuracin siempre se guarda en un fichero externo
    File dir = new File(System.getProperty(USER_HOME) + File.separator + getNombreDirExterno());
    if ((!dir.exists()) || (!dir.isDirectory())) {
        if (!dir.mkdir())
            return;
    }
    File fichero = new File(dir, getNombreFicheroExterno());
    log.trace("Salva fichero de configuracin en: " + fichero.getAbsolutePath());
    if (!fichero.exists()) {
        // Si el fichero externo no existe se crea fuera un copia
        // del fichero almacenado dentro del jar
        InputStream fis = getClass().getResourceAsStream(FICHERO_PROPIEDADES);
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream(fichero);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int length = bis.available();
        byte[] datos = new byte[length];
        bis.read(datos);
        bos.write(datos);
        bos.flush();
        bos.close();
        bis.close();
    }
    // AppPerfect: Falso positivo
    BufferedReader propiedades = new BufferedReader(new FileReader(fichero));

    linea = propiedades.readLine();
    while (linea != null) {
        StringTokenizer token = new StringTokenizer(linea, IGUAL);
        if (token.hasMoreTokens()) {
            String clave = token.nextToken().trim();
            if (configuracion.containsKey(clave)) {
                paraGrabar.append(clave);
                paraGrabar.append(IGUAL_ESPACIADO);
                paraGrabar.append(getValor(clave));
                paraGrabar.append(CRLF);
            } else {
                paraGrabar.append(linea);
                paraGrabar.append(CRLF);

            }
        } else
            paraGrabar.append(CRLF);
        linea = propiedades.readLine();
    }
    propiedades.close();

    //AppPerfect: Falso positivo
    FileWriter fw = new FileWriter(fichero);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(String.valueOf(paraGrabar));
    bw.flush();
    bw.close();

}

From source file:truesculpt.ui.panels.WebFilePanel.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getManagers().getUtilsManager().updateFullscreenWindowStatus(getWindow());

    setContentView(R.layout.webfile);/*  w ww  . j  a v a2  s  . c  o m*/

    getManagers().getUsageStatisticsManager().TrackEvent("OpenFromWeb", "", 1);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.setWebViewClient(new MyWebViewClient());
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JavaScriptInterface(this, getManagers()), "Android");

    int nVersionCode = getManagers().getUpdateManager().getCurrentVersionCode();
    mWebView.loadUrl(mStrBaseWebSite + "?version=" + nVersionCode);

    mPublishToWebBtn = (Button) findViewById(R.id.publish_to_web);
    mPublishToWebBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name = getManagers().getMeshManager().getName();
            final File imagefile = new File(getManagers().getFileManager().GetImageFileName());
            final File objectfile = new File(getManagers().getFileManager().GetObjectFileName());

            getManagers().getUsageStatisticsManager().TrackEvent("PublishToWeb", name, 1);

            if (imagefile.exists() && objectfile.exists()) {
                try {
                    final File zippedObject = File.createTempFile("object", "zip");
                    zippedObject.deleteOnExit();

                    BufferedReader in = new BufferedReader(new FileReader(objectfile));
                    BufferedOutputStream out = new BufferedOutputStream(
                            new GZIPOutputStream(new FileOutputStream(zippedObject)));
                    System.out.println("Compressing file");
                    int c;
                    while ((c = in.read()) != -1) {
                        out.write(c);
                    }
                    in.close();
                    out.close();

                    long size = 0;

                    size = new FileInputStream(imagefile).getChannel().size();
                    size += new FileInputStream(zippedObject).getChannel().size();
                    size /= 1000;

                    final SpannableString msg = new SpannableString(
                            "You will upload your latest saved version of this scupture representing " + size
                                    + " ko of data\n\n"
                                    + "When clicking the yes button you accept to publish your sculpture under the terms of the creative commons share alike, non commercial license\n"
                                    + "http://creativecommons.org/licenses/by-nc-sa/3.0"
                                    + "\n\nDo you want to proceed ?");
                    Linkify.addLinks(msg, Linkify.ALL);

                    AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this);
                    builder.setMessage(msg).setCancelable(false)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {
                                    PublishPicture(imagefile, zippedObject, name);
                                }
                            }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                    AlertDialog dlg = builder.create();
                    dlg.show();

                    // Make the textview clickable. Must be called after
                    // show()
                    ((TextView) dlg.findViewById(android.R.id.message))
                            .setMovementMethod(LinkMovementMethod.getInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this);
                builder.setMessage(
                        "File has not been saved, you need to save it before publishing\nDo you want to proceed to save window ?")
                        .setCancelable(false)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                ((FileSelectorPanel) getParent()).getTabHost().setCurrentTab(2);
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                builder.show();
            }
        }
    });
}

From source file:org.iti.agrimarket.service.OfferProductRestController.java

/**
 * is responsible to Get add offer//w  ww .  j  a va 2 s .co  m
 *
 * @author Muhammad
 * @param offer it's belongs to UserOfferProduct class mapping all its
 * properties
 * @return JSON Success word if added successfully or some of error codes
 */
@RequestMapping(value = ADD_OFFER_URL, method = RequestMethod.POST)
public Response addOffer(@RequestBody String offer) {

    //convert JSON parameter to Object
    UserOfferProductFixed offerProductFixed = paramExtractor.getParam(offer, UserOfferProductFixed.class);

    if (offerProductFixed != null && offerProductFixed.getProduct() != null
            && offerProductFixed.getUser() != null && offerProductFixed.getUser().getId() != 0
            && offerProductFixed.getUnitByUnitId() != null
            && offerProductFixed.getUnitByUnitId().getId() != null
            && offerProductFixed.getUnitByPricePerUnitId() != null
            && offerProductFixed.getUnitByPricePerUnitId().getId() != null
            && offerProductFixed.getStartDate() != null) {
        offerProductFixed.setRecommended(false);
        //check if product & user & unit are already exists! 
        User userObject = userService.getUser(offerProductFixed.getUser().getId());
        Product product = productServiceInterface.getProduct(offerProductFixed.getProduct().getId());
        Unit unit = unitService.getUnit(offerProductFixed.getUnitByUnitId().getId());

        if (userObject == null || product == null || unit == null) {
            logger.error(Constants.INVALID_PARAM);
            return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
        }
        //            offerProductFixed.setImageUrl("images" + file.getName());
        int check = offerService.addOffer(offerProductFixed);
        if (check == -1) // if the object doesn't added
        {
            logger.error(Constants.DB_ERROR);
            return Response.status(Constants.DB_ERROR).build();
        }
        String name = offerProductFixed.getId() + String.valueOf(new Date().getTime());
        if (offerProductFixed.getImage() != null) {
            try {
                byte[] bytes = offerProductFixed.getImage();
                MagicMatch match = Magic.getMagicMatch(bytes);
                final String ext = "." + match.getExtension();

                File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH);
                if (!parentDir.isDirectory()) {
                    parentDir.mkdirs();
                }

                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.OFFER_PATH + name)));
                stream.write(bytes);

                stream.close();
                offerProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + name + ext);
                offerService.updateOffer(offerProductFixed);
            } catch (Exception e) {
                logger.error(e.getMessage());
                offerService.deleteOffer(check); // delete the offer if something goes wrong
                return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
            }
        } else {
            logger.error(Constants.IMAGE_UPLOAD_ERROR);
            offerService.deleteOffer(check); // delete the offer if something goes wrong
            return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build();
        }
        //if request happened successfully.
        return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build();
    } else {
        // if there are invalid or missing parameters
        logger.error(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet//  w w w .ja v a 2  s.  com
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

From source file:com.fluidops.iwb.deepzoom.ImageLoader.java

/**
 * Loads an image from a URL to a local file
 * @param uri - The URL from which to obtain the image
 * @param file - The file to store the image to
 * @return/* w  w w. ja v  a 2 s  .c  om*/
 */

public boolean loadGoogleImage(URI uri, Map<URI, Set<Value>> facets, File file) {
    String url;
    URL u;
    InputStream is = null;
    BufferedInputStream dis = null;
    int b;
    try {
        URL googleUrl;
        ReadDataManager dm = EndpointImpl.api().getDataManager();
        String label = dm.getLabel(uri);
        // TODO: currently hard coded logic for data sets 
        // should find more flexible logic
        if (uri.stringValue().startsWith("http://www.ckan.net/"))
            label += " logo";

        googleUrl = new URL("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&" + "q="
                + URLEncoder.encode(label, "UTF-8"));

        URLConnection connection = googleUrl.openConnection();
        connection.addRequestProperty("Referer", "http://iwb.fluidops.com/");

        String content = GenUtil.readUrl(connection.getInputStream());

        try {
            JSONObject json = new JSONObject(content);

            JSONObject response = json.getJSONObject("responseData");
            JSONArray results = response.getJSONArray("results");
            JSONObject result = results.getJSONObject(0);
            url = result.getString("unescapedUrl");

        }

        catch (JSONException e) {
            return false;
        }

        u = new URL(url);

        try {
            is = u.openStream();
        } catch (IOException e) {
            System.out.println("File could not be found: " + url);

            // quick fix: 200px-Image n/a, try smaller pic (for Wikipedia images)
            url = url.replace("200px", "94px");
            u = new URL(url);
            try {
                is = u.openStream();
            } catch (IOException e2) {
                System.out.println("also smaller image not available");
                return false;
            }
        }
        dis = new BufferedInputStream(is);
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            while ((b = dis.read()) != -1) {
                out.write(b);
            }
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }
    } catch (MalformedURLException mue) {
        logger.error(mue.getMessage(), mue);
        return false;

    } catch (IOException ioe) {
        logger.error(ioe.getMessage(), ioe);
        return false;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(dis);
    }
    return true;
}

From source file:de.document.service.MedikamentService.java

public String transferToFile(MultipartFile file) throws Throwable {
    String filePath2 = Thread.currentThread().getContextClassLoader().getResource("medikament") + "\\"
            + file.getOriginalFilename();
    String filePath = filePath2.substring(6);

    if (!file.isEmpty()) {
        try {/*w ww. j  a  va2 s .  c om*/
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            return filePath;

        } catch (Exception e) {
            System.out.println("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
        }
    } else {
        System.out
                .println("You failed to upload " + file.getOriginalFilename() + " because the file was empty.");
    }
    return null;
}

From source file:com.ibm.iotf.sample.devicemgmt.device.HTTPFirmwareDownload.java

public String downloadFirmware() {
    System.out.println(CLASS_NAME + ": Firmware Download start...");
    boolean success = false;
    URL firmwareURL = null;//from w  w  w  .j a  v  a 2s  . c o m
    URLConnection urlConnection = null;
    String downloadedFirmwareName = null;

    Properties props = new Properties();
    try {
        props.load(HTTPFirmwareDownload.class.getResourceAsStream(PROPERTIES_FILE_NAME));
    } catch (IOException e1) {
        System.err.println("Not able to read the properties file, exiting..");
        System.exit(-1);
    }

    String username = trimedValue(props.getProperty("User-Name"));
    String password = trimedValue(props.getProperty("Password"));
    String dbName = trimedValue(props.getProperty("Repository-DB"));

    /**
     * start downloading the firmware image
     */
    try {
        System.out.println(CLASS_NAME + ": Downloading Firmware from URL " + deviceFirmware.getUrl());

        firmwareURL = new URL(deviceFirmware.getUrl());
        urlConnection = firmwareURL.openConnection();

        byte[] encoding = Base64.encodeBase64(new String(username + ":" + password).getBytes());
        String encodedString = "Basic " + new String(encoding);

        urlConnection.setRequestProperty("Authorization", encodedString);

        int fileSize = urlConnection.getContentLength();
        if (deviceFirmware.getName() != null && !"".equals(deviceFirmware.getName())) {
            downloadedFirmwareName = deviceFirmware.getName();
        } else {
            // use the timestamp as the name
            downloadedFirmwareName = "firmware_" + new Date().getTime() + ".deb";
        }

        File file = new File(downloadedFirmwareName);
        BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName()));

        // count the download size to send the progress report as DiagLog to Watson IoT Platform
        int downloadedSize = 0;

        int data = bis.read();
        downloadedSize += 1;

        if (data != -1) {
            bos.write(data);
            byte[] block = new byte[1024 * 10];
            int previousProgress = 0;
            while (true) {
                int len = bis.read(block, 0, block.length);
                downloadedSize = downloadedSize + len;
                if (len != -1) {
                    // Send the progress update
                    if (fileSize > 0) {
                        int progress = (int) (((float) downloadedSize / fileSize) * 100);
                        if (progress > previousProgress) {
                            String message = "Firmware Download progress: " + progress + "%";
                            addDiagLog(message, new Date(), LogSeverity.informational);
                            System.out.println(message);
                        }
                    } else {
                        // If we can't retrieve the filesize, let us update how much we have download so far
                        String message = "Downloaded : " + downloadedSize + " bytes so far";
                        addDiagLog(message, new Date(), LogSeverity.informational);
                        System.out.println(message);
                    }
                    bos.write(block, 0, len);
                } else {
                    break;
                }
            }
            bos.close();
            bis.close();

            success = true;
        } else {
            //There is no data to read, so throw an exception
            if (requirePlatformUpdate) {
                deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI);
            }
        }

        // Verify the firmware image if verifier is set
        if (deviceFirmware.getVerifier() != null && !deviceFirmware.getVerifier().equals("")) {
            success = verifyFirmware(file, deviceFirmware.getVerifier());

            /**
             * As per the documentation, If a firmware verifier has been set, the device should 
             * attempt to verify the firmware image. 
             * 
             * If the image verification fails, mgmt.firmware.state should be set to 0 (Idle) 
             * and mgmt.firmware.updateStatus should be set to the error status value 4 (Verification Failed).
             */
            if (success == false) {
                if (requirePlatformUpdate) {
                    deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.VERIFICATION_FAILED);
                }
                // the firmware state is updated to IDLE below
            }
        }

    } catch (MalformedURLException me) {
        // Invalid URL, so set the status to reflect the same,
        if (requirePlatformUpdate) {
            deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI);
        }
        me.printStackTrace();
    } catch (IOException e) {
        if (requirePlatformUpdate) {
            deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.CONNECTION_LOST);
        }
        e.printStackTrace();
    } catch (OutOfMemoryError oom) {
        if (requirePlatformUpdate) {
            deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.OUT_OF_MEMORY);
        }
    }

    /**
     * Set the firmware download and possibly the firmware update status
     * (will be sent later) accordingly
     */
    if (success == true) {
        if (requirePlatformUpdate) {
            deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.SUCCESS);
            deviceFirmware.setState(FirmwareState.DOWNLOADED);
        }
    } else {
        if (requirePlatformUpdate) {
            deviceFirmware.setState(FirmwareState.IDLE);
        }
        return null;
    }

    System.out.println(CLASS_NAME + ": Firmware Download END...(" + success + ")");
    return downloadedFirmwareName;
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void getCaptcha(String image) {

    try {/*from w  w  w . j a  va2 s .c  o m*/
        URL obj = new URL(image);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.addRequestProperty("Connection", "keep-alive");

        con.getResponseCode();
        tokenCookie = con.getHeaderField("Set-Cookie");

        // creating the input stream from google image
        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
        // my local file writer, output stream
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Captcha.png"));
        // until the end of data, keep saving into file.
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
        out.flush();
        in.close();
        out.close();
        con.disconnect();
    } catch (MalformedURLException e) {

    } catch (IOException e) {
        // TODO: handle exception
    }

}

From source file:BackupFiles.java

/**
 * Copies a file/* ww  w. ja  va 2  s  . co m*/
 * 
 * @param file
 *            the file to copy
 * @param targetDir
 *            the directory to copy to
 */
private void copyFile(File file, File targetDir) {
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    File destFile = new File(targetDir.getAbsolutePath() + File.separator + file.getName());
    try {
        showMessage("Copying " + file.getName());
        in = new BufferedInputStream(new FileInputStream(file));
        out = new BufferedOutputStream(new FileOutputStream(destFile));
        int n;
        while ((n = in.read()) != -1) {
            out.write(n);
        }
        showMessage("Copied " + file.getName());
    } catch (Exception e) {
        showMessage("Cannot copy file " + file.getAbsolutePath());
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        if (out != null)
            try {
                out.close();
            } catch (Exception e) {
            }
    }
}