Example usage for java.io FileOutputStream write

List of usage examples for java.io FileOutputStream write

Introduction

In this page you can find the example usage for java.io FileOutputStream write.

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this file output stream.

Usage

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

private static MultipartEntity getMultipartEntity(HttpServletRequest request) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        String value = request.getParameter(name);
        try {//from www  . j  av a  2s.  c  o m
            if (name.equals("file")) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);// 10 Mo
                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(item.getName());
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(item.get());
                    fos.flush();
                    fos.close();
                    entity.addPart(name, new FileBody(file, "application/zip"));
                }
            } else {
                entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8")));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileUploadException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    return entity;

}

From source file:org.paxml.selenium.rc.FileServer.java

/**
 * Host a string as file content, preferrably in a system temp file. If
 * system temp file does not work, host in memory. In either case, a file is
 * readable for only once./*from   w  w  w .j a  va2  s  .co m*/
 * 
 * @param content
 *            the file content
 * @return the hosted path
 */
public static String hostFileContent(String content) {
    String path;
    File file;
    try {
        File dir = new File(TMP_DIR);
        dir.mkdirs();
        file = File.createTempFile(FileServer.class.getSimpleName() + "_", ".tmp", dir);
        file.deleteOnExit();

        FileOutputStream fout = new FileOutputStream(file, false);
        try {
            fout.write(content.getBytes("UTF-8"));
            fout.flush();
        } finally {
            IOUtils.closeQuietly(fout);
        }
        path = TMP_FILE_IDENT + file.getName();

    } catch (IOException e) {
        path = IN_MEM_IDENT + UUID.randomUUID().toString() + ".txt";
        if (null != memFiles.putIfAbsent(path, content)) {
            throw new RuntimeException("Duplicated in memory fike key: " + path);
        }

    }
    if (log.isDebugEnabled()) {
        log.debug("File content held in: " + path);
    }
    return path;

}

From source file:org.ambientdynamix.web.WebUtils.java

/**
 * xports an certificate to a file./* w w w .jav a  2s.c o m*/
 * 
 * @param cert
 *            The certificate to export.
 * @param file
 *            The destination file.
 * @param binary
 *            True if the cert should be written as a binary file; false to encode using Base64.
 */
public static void exportCertificate(java.security.cert.Certificate cert, File file, boolean binary) {
    Log.i(TAG, "Writing cert to: " + file.getAbsolutePath());
    try {
        // Get the encoded form which is suitable for exporting
        byte[] buf = cert.getEncoded();
        FileOutputStream os = new FileOutputStream(file);
        if (binary) {
            // Write in binary form
            os.write(buf);
        } else {
            // Write in text form
            Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
            wr.write("-----BEGIN CERTIFICATE-----\n");
            Base64.encodeBase64(buf);
            wr.write("\n-----END CERTIFICATE-----\n");
            wr.flush();
        }
        os.close();
    } catch (Exception e) {
        Log.w(TAG, "Error writing cert for " + file);
    }
}

From source file:com.bc.fiduceo.TestUtil.java

public static void writeStringTo(File outFile, String data) throws IOException {
    FileOutputStream outputStream = null;
    try {/*from   w  w  w . j  av  a  2  s.c  o m*/
        outputStream = new FileOutputStream(outFile);
        outputStream.write(data.getBytes());
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:org.ligi.android.dubwise_uavtalk.dashboard.DownloadDashboardImagesStatusAlertDialog.java

/**
 * /*w  ww  . j  a va2s . c  o  m*/
 * @param activity
 * @param autoclose - if the alert should close when connection is established
 * 
 */
public static void show(Context activity, boolean autoclose, Intent after_connection_intent) {

    LinearLayout lin = new LinearLayout(activity);
    lin.setOrientation(LinearLayout.VERTICAL);

    ScrollView sv = new ScrollView(activity);
    TextView details_text_view = new TextView(activity);

    LinearLayout lin_in_scrollview = new LinearLayout(activity);
    lin_in_scrollview.setOrientation(LinearLayout.VERTICAL);
    sv.addView(lin_in_scrollview);
    lin_in_scrollview.addView(details_text_view);

    details_text_view.setText("no text");

    ProgressBar progress = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
    progress.setMax(img_lst.length);

    lin.addView(progress);
    lin.addView(sv);

    new AlertDialog.Builder(activity).setTitle("Download Status").setView(lin)
            .setPositiveButton("OK", new DialogDiscardingOnClickListener()).show();

    class AlertDialogUpdater implements Runnable {

        private Handler h = new Handler();
        private TextView myTextView;
        private ProgressBar myProgress;

        public AlertDialogUpdater(TextView ab, ProgressBar progress) {
            myTextView = ab;
            myProgress = progress;

        }

        public void run() {

            for (int i = 0; i < img_lst.length; i++) {
                class MsgUpdater implements Runnable {

                    private int i;

                    public MsgUpdater(int i) {
                        this.i = i;
                    }

                    public void run() {
                        myProgress.setProgress(i + 1);
                        if (i != img_lst.length - 1)
                            myTextView.setText("Downloading " + img_lst[i] + ".png");
                        else
                            myTextView.setText("Ready - please restart DUBwise to apply changes!");
                    }
                }
                h.post(new MsgUpdater(i));

                try {
                    URLConnection ucon = new URL(url_lst[i]).openConnection();
                    BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());

                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1)
                        baf.append((byte) current);

                    File path = new File(
                            Environment.getExternalStorageDirectory() + "/dubwise/images/dashboard");
                    path.mkdirs();

                    FileOutputStream fos = new FileOutputStream(
                            new File(path.getAbsolutePath() + "/" + img_lst[i] + ".png"));
                    fos.write(baf.toByteArray());
                    fos.close();
                } catch (Exception e) {
                }

                try {
                    Thread.sleep(199);
                } catch (InterruptedException e) {
                }

            }
        }
    }

    new Thread(new AlertDialogUpdater(details_text_view, progress)).start();
}

From source file:com.zuora.api.util.ZuoraUtility.java

/**
 * Write file.// w  w  w.  j ava 2 s. c  o m
 * 
 * @param data
 *          the data
 */
public static void writeFile(byte[] data) {
    ZuoraUtility utility = new ZuoraUtility();
    new File(utility.getPropertyValue(FILE_PATH)).mkdirs();
    String strFilePath = utility.getPropertyValue(FILE_PATH) + "INV-" + System.currentTimeMillis() + ".pdf";
    try {
        FileOutputStream fos = new FileOutputStream(strFilePath);
        fos.write(data);
        fos.close();
        System.out.println("Invoice PDF generated @ " + strFilePath);
    } catch (FileNotFoundException ex) {
        System.out.println("FileNotFoundException : " + ex);
    } catch (IOException ioe) {
        System.out.println("IOException : " + ioe);
    }
}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreFileUtil.java

public static void writePkcsFile(String b64P12, String p12fileName) throws IOException {

    if (StringUtils.isBlank(p12fileName) || StringUtils.isBlank(b64P12)) {
        return;//from w  w w .  j av  a 2  s  . com
    }
    byte[] p12File = Base64.decodeBase64(b64P12);
    FileOutputStream fos = new FileOutputStream(p12fileName);
    fos.write(p12File);
    fos.flush();
    fos.close();
}

From source file:com.taobao.android.builder.tools.asm.ClassNameRenamer.java

public static void rewriteDataBinderMapper(File dir, String fromName, String toName, File Clazz)
        throws IOException {
    FileInputStream fileInputStream = new FileInputStream(Clazz);
    ClassReader in1 = new ClassReader(fileInputStream);
    ClassWriter cw = new ClassWriter(0);

    Set<String> renames = new HashSet<String>();
    renames.add(fromName);/*from w  w  w .  j a  v a  2 s . co m*/
    in1.accept(new ClassRenamer(cw, renames, toName), 8);

    File destClass = new File(dir, toName + ".class");
    destClass.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(destClass);
    fileOutputStream.write(cw.toByteArray());
    IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(fileInputStream);

}

From source file:Main.java

public static boolean writeToSdcard(byte[] data, String path, String fileName) {
    FileOutputStream fos = null;
    try {// w  w w. jav a2  s.  c o m
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        File file = new File(path + fileName);
        if (file.exists()) {
            file.delete();
        }
        fos = new FileOutputStream(file);
        fos.write(data);
        fos.flush();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.archive.modules.fetcher.AbstractCookieStorage.java

public static void saveCookies(String saveCookiesFile, Map<String, Cookie> cookies) {
    // Do nothing if cookiesFile is not specified. 
    if (saveCookiesFile == null || saveCookiesFile.length() <= 0) {
        return;/*from   w  ww. ja v  a 2  s. co  m*/
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(new File(saveCookiesFile));
        String tab = "\t";
        out.write("# Heritrix Cookie File\n".getBytes());
        out.write("# This file is the Netscape cookies.txt format\n\n".getBytes());
        for (Cookie cookie : cookies.values()) {
            // Guess an initial size 
            MutableString line = new MutableString(1024 * 2);
            line.append(cookie.getDomain());
            line.append(tab);
            line.append(cookie.isDomainAttributeSpecified() ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getPath());
            line.append(tab);
            line.append(cookie.getSecure() ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getExpiryDate() != null ? cookie.getExpiryDate().getTime() / 1000 : -1);
            line.append(tab);
            line.append(cookie.getName());
            line.append(tab);
            line.append(cookie.getValue() != null ? cookie.getValue() : "");
            line.append("\n");
            out.write(line.toString().getBytes());
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to write " + saveCookiesFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}