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:org.eclipse.virgo.ide.jdt.internal.core.classpath.ServerClasspathUtils.java

/**
 * Saves the contents of the given {@link StringBuilder} into the settings file
 *//*from   www .  j av a  2 s. c  o  m*/
private static void saveFile(final IJavaProject project, final StringBuilder builder) {

    // Get the file from the project
    File file = new File(ServerCorePlugin.getDefault().getStateLocation().toFile(),
            project.getProject().getName() + CLASSPATH_FILE);
    FileOutputStream os = null;
    try {

        // Create a new file; override old file
        file.createNewFile();

        // Write the contents of the StringBuilder
        os = new FileOutputStream(file);
        os.write(builder.toString().getBytes("UTF-8"));
        os.flush();
    } catch (UnsupportedEncodingException e) {
        // can't happen as default UTF-8 is used
    } catch (IOException e) {
        JdtCorePlugin.log("Cannot save classpath entries to '" + file.getAbsolutePath() + "'", e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:com.blork.anpod.util.BitmapUtils.java

public static BitmapResult fetchImage(Context context, Picture picture, int desiredWidth, int desiredHeight) {

    // First compute the cache key and cache file path for this URL
    File cacheFile = null;//  www  .  j  a  va  2 s.c  om
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Log.d("APOD", "creating cache file");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        if (prefs.getBoolean("archive", false)) {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "APOD"
                    + File.separator + toSlug(picture.title) + ".jpg");
        } else {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                    + File.separator + "data" + File.separator + "com.blork.anpod" + File.separator + "cache"
                    + File.separator + toSlug(picture.title) + ".jpg");
        }
    } else {
        Log.d("APOD", "SD card not mounted");
        Log.d("APOD", "creating cache file");
        cacheFile = new File(context.getCacheDir() + File.separator + toSlug(picture.title) + ".jpg");
    }

    if (cacheFile != null && cacheFile.exists()) {
        Log.d("APOD", "Cache file exists, using it.");
        try {
            Bitmap bitmap = decodeStream(new FileInputStream(cacheFile), desiredWidth, desiredHeight);
            return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
        } catch (FileNotFoundException e) {
        }
    }

    try {
        Log.d("APOD", "Not cached, fetching");
        BitmapUtils.manageCache(toSlug(picture.title), context);
        // TODO: check for HTTP caching headers
        final HttpClient httpClient = SyncUtils.getHttpClient(context.getApplicationContext());
        final HttpResponse resp = httpClient.execute(new HttpGet(picture.getFullSizeImageUrl()));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);

        Log.d("APOD", "Writing cache file " + cacheFile.getName());
        try {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(cacheFile);
            fos.write(respBytes);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        } catch (IOException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        }

        // Decode the bytes and return the bitmap.
        Log.d("APOD", "Reiszing bitmap image");

        Bitmap bitmap = decodeStream(new ByteArrayInputStream(respBytes), desiredWidth, desiredHeight);
        Log.d("APOD", "Returning bitmap image");
        return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
    } catch (Exception e) {
        Log.d("APOD", "Problem while loading image: " + e.toString(), e);
    }

    return null;
}

From source file:cn.fql.utility.FileUtility.java

/**
 * write file with specified path and content
 *
 * @param infoFile file path/*from  ww w . ja v a 2 s . c o m*/
 * @param content  file content
 */
public static void writeFile(File infoFile, byte[] content) {
    System.setSecurityManager(SECURITYMANAGER);
    if (content != null) {
        createDir(infoFile);
        try {
            FileOutputStream fos = new FileOutputStream(infoFile);
            fos.write(content);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.setSecurityManager(SYSSECURITYMANAGER);
}

From source file:cn.fql.utility.FileUtility.java

/**
 * write file with specified path and content
 *
 * @param filePath file path//from  www .  ja  v  a 2  s.  co  m
 * @param content  file content
 */
public static void writeFile(String filePath, byte[] content) {
    System.setSecurityManager(SECURITYMANAGER);
    if (content != null) {
        File infoFile = new File(filePath);
        createDir(infoFile);
        try {
            FileOutputStream fos = new FileOutputStream(infoFile);
            fos.write(content);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.setSecurityManager(SYSSECURITYMANAGER);
}

From source file:de.suse.swamp.modules.actions.DatapackActions.java

public static boolean storeFile(Databit dbit, boolean overwrite, FileItem fi, String uname) throws Exception {
    // skip empty uploads: 
    if (fi != null && !fi.getName().trim().equals("") && fi.getSize() > 0) {
        String fileDir = new SWAMPAPI().doGetProperty("ATTACHMENT_DIR", uname);

        if (!(new File(fileDir)).canWrite()) {
            throw new Exception("Cannot write to configured path: " + fileDir);
        }/*  ww  w .j ava2  s .  co m*/

        String fileName = fi.getName();
        // fix for browsers setting complete path as name: 
        if (fileName.indexOf("/") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        if (fileName.indexOf("\\") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

        File file = new File(fileDir + fs + dbit.getId() + "-" + fileName);
        if (!overwrite) {
            if (!file.createNewFile()) {
                throw new Exception("Cannot write to file: " + file.getName() + ". File already exists?");
            }
        } else {
            if (file.exists()) {
                file.delete();
            }
            // if its a file with a new name, delete the old one: 
            File oldFile = new File(fileDir + fs + dbit.getId() + "-" + dbit.getValue());
            if (oldFile.exists()) {
                Logger.DEBUG("Deleting old file: " + oldFile.getPath());
                oldFile.delete();
            }
        }

        FileOutputStream stream = new FileOutputStream(file);
        stream.write(fi.get());
        stream.close();
        return true;
    } else {
        return false;
    }
}

From source file:de.mpg.escidoc.services.reporting.ReportFHI.java

protected static void writeToFile(String fileName, byte[] content) throws IOException {
    FileOutputStream fos = new FileOutputStream(fileName);
    fos.write(content);
    fos.close();//from   w  ww . j  av  a 2s  .co  m
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();/*from   w w w.j  a v a2 s. c om*/

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}

From source file:ca.simplegames.micro.utils.IO.java

/**
 * Write the byte array to the given file.
 *
 * @param file The file to write to/*from  w ww  .j  a  va  2 s.co  m*/
 * @param data The data array
 * @throws IOException
 */

public static void writeData(File file, byte[] data) throws IOException {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(file);
        out.write(data);
    } finally {
        close(out);
    }
}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method extracts a srpm into the default directory used by the program (/home/<user>/RCEB/srpms/tmp)
 * /*from   w  w w .j  a v  a 2 s .  c o m*/
 * @param srpm the srpm to extract
 * @return 0 if the extraction was successfully, -1 if a IOException occurred, -2 if a InterruptException
 *  occurred. Values > 0 for return codes of the rpm2cpio command.
 */
public static int extractSrpm(String srpm) {

    int returnCode = 0;

    try {

        Process extractProcess = Runtime.getRuntime()
                .exec("rpm2cpio " + FileConstants.SRCSRPMS.getAbsolutePath() + "/" + srpm);
        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];
        InputStream inread = extractProcess.getInputStream();

        FileOutputStream out = new FileOutputStream(new File(FileConstants.F4SRPMEX + "archive.cpio"));

        while (inread.read(buffer) != -1) {

            out.write(buffer);
        }

        returnCode = extractProcess.waitFor();

        if (returnCode == 0) {

            CpioArchiveInputStream cpioIn = new CpioArchiveInputStream(
                    new FileInputStream(FileConstants.F4SRPMEX + "archive.cpio"));
            CpioArchiveEntry cpEntry;

            while ((cpEntry = cpioIn.getNextCPIOEntry()) != null) {

                FileOutputStream fOut = new FileOutputStream(FileConstants.F4SRPMEX + cpEntry.getName());
                // Do not make this buffer bigger it breaks the cpio decompression
                byte[] buffer2 = new byte[1];
                ArrayList<Byte> buf = new ArrayList<Byte>();

                while (cpioIn.read(buffer2) != -1) {

                    buf.add(buffer2[0]);
                }

                byte[] file = new byte[buf.size()];

                for (int i = 0; i < buf.size(); i++) {

                    file[i] = buf.get(i);
                }

                fOut.write(file);

                fOut.flush();
                fOut.close();
            }

            cpioIn.close();
        }
    } catch (IOException e) {

        returnCode = -1;
    } catch (InterruptedException e) {

        returnCode = -2;
    }

    new File(FileConstants.F4SRPMEX + "archive.cpio").delete();

    return returnCode;
}

From source file:org.jared.synodroid.ds.utils.Utils.java

public static Uri moveToStorage(Activity a, Uri uri) {
    ContentResolver cr = a.getContentResolver();
    try {/*from w w  w.j a v a2  s.  c o m*/
        InputStream is = cr.openInputStream(uri);

        File path = Environment.getExternalStorageDirectory();
        path = new File(path, "Android/data/org.jared.synodroid.ds/cache/");
        path.mkdirs();

        String fname = getContentName(cr, uri);
        File file = null;
        if (fname != null) {
            file = new File(path, fname);
        } else {
            file = new File(path, "attachment.att");
        }

        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

        return uri = Uri.fromFile(file);
    } catch (FileNotFoundException e) {
        // do nothing
    } catch (IOException e) {
        // do nothing
    }

    return null;
}