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[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this file output stream.

Usage

From source file:controlador.Red.java

/**
 * Get de un fichero desde el Server al Cliente Local.
 * @param rutaLocal Ruta en la cual se creara el fichero.
 * @param name Nombre con el cual se busca el fichero en el server y se crea en local.
 * @return Estado de la operacion./*w w  w  .  jav a2  s . c o  m*/
 */
public static boolean getFile(String rutaLocal, String name) {
    try {
        url = new URL(conexion + name);
        URLConnection urlConn = url.openConnection();
        InputStream is = urlConn.getInputStream();
        FileOutputStream fos = new FileOutputStream(rutaLocal + name);
        byte[] buffer = new byte[BUFFER_LENGTH];

        int count;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
        }
        fos.flush();

        is.close();
        fos.close();

        return true;
    } catch (IOException ex) {
        System.out.println("Problema al recibir un fichero desde el Server: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:com.storageroomapp.client.util.FileUtil.java

static public boolean writeStreamToFile(File fileToWrite, InputStream is, boolean closeIS) {
    boolean success = true;

    FileOutputStream fos = null;
    try {//from   w w  w  .j  av a  2s  .  c o m
        fos = new FileOutputStream(fileToWrite);
        if (is != null) {
            byte[] buffer = new byte[16384];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        }
    } catch (IOException ioe) {
        log.error("Error writing a stream to a file", ioe);
        success = false;
    } finally {
        if (closeIS && (is != null)) {
            try {
                is.close();
            } catch (IOException ioe) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:com.twosigma.beakerx.kernel.magic.command.ClasspathAddMvnDepsCellMagicCommandTest.java

private static void unzipRepo() {
    try {/*from w  w w .  j a v  a 2s  .  c  o  m*/
        ZipFile zipFile = new ZipFile(BUILD_PATH + "/testMvnCache.zip");
        Enumeration<?> enu = zipFile.entries();
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            String name = BUILD_PATH + "/" + zipEntry.getName();
            File file = new File(name);
            if (name.endsWith("/")) {
                file.mkdirs();
                continue;
            }

            File parent = file.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }

            InputStream is = zipFile.getInputStream(zipEntry);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) >= 0) {
                fos.write(bytes, 0, length);
            }
            is.close();
            fos.close();

        }
        zipFile.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:OCRRestAPI.java

private static void DownloadConvertedFile(String outputFileUrl) throws IOException {
    URL downloadUrl = new URL(outputFileUrl);
    HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection();

    if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

        InputStream inputStream = downloadConnection.getInputStream();

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc");

        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }/*  www  .ja  v  a2  s .  co m*/

        outputStream.close();
        inputStream.close();
    }

    downloadConnection.disconnect();
}

From source file:Main.java

public static void writeFile(File file, byte[] content) throws IOException {
    if (!file.exists()) {
        try {//w  w  w . j  av  a 2s .c o m
            file.createNewFile();
        } catch (IOException e) {
            throw new IOException("not crete file=" + file.getAbsolutePath());
        }
    }
    FileOutputStream fileOutputStream = null;
    ByteArrayInputStream bis = null;
    try {
        bis = new ByteArrayInputStream(content);
        fileOutputStream = new FileOutputStream(file, false);
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = bis.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, length);
        }
        fileOutputStream.flush();
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }
}

From source file:Main.java

private static boolean copyAsset(AssetManager am, File rep, boolean force) {
    boolean existingInstall = false;
    try {/*w ww.j a va 2s .  c o  m*/
        String assets[] = am.list("");
        for (int i = 0; i < assets.length; i++) {
            boolean hp48 = assets[i].equals("hp48");
            boolean hp48s = assets[i].equals("hp48s");
            boolean ram = assets[i].equals("ram");
            boolean rom = assets[i].equals("rom");
            boolean rams = assets[i].equals("rams");
            boolean roms = assets[i].equals("roms");
            int required = 0;
            if (ram)
                required = 131072;
            else if (rams)
                required = 32768;
            else if (rom)
                required = 524288;
            else if (roms)
                required = 262144;
            //boolean SKUNK = assets[i].equals("SKUNK");
            if (hp48 || rom || ram || hp48s || roms || rams) {
                File fout = new File(rep, assets[i]);
                existingInstall |= fout.exists();
                if (!fout.exists() || fout.length() == 0 || (required > 0 && fout.length() != required)
                        || force) {
                    Log.i("x48", "Overwriting " + assets[i]);
                    FileOutputStream out = new FileOutputStream(fout);
                    InputStream in = am.open(assets[i]);
                    byte buffer[] = new byte[8192];
                    int n = -1;
                    while ((n = in.read(buffer)) > -1) {
                        out.write(buffer, 0, n);
                    }
                    out.close();
                    in.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return existingInstall;
}

From source file:Main.java

public static void DownloadFile(String u) {
    try {/*from   w w  w.j a v  a  2 s  . c  o m*/
        Logd(TAG, "Starting download of: " + u);
        URL url = new URL(u);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        //File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        checkStorageDir();
        File storageDir = new File(
                Environment.getExternalStorageDirectory() + "/Android/data/com.nowsci.odm/.storage");
        File file = new File(storageDir, getFileName(u));
        Logd(TAG, "Storage directory: " + storageDir.toString());
        Logd(TAG, "File name: " + file.toString());
        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        Logd(TAG, "File written");
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.hangum.tadpole.engine.initialize.TadpoleSystemInitializer.java

/**
 * system  ./*  w  w  w.ja v a  2 s.  c  om*/
 * 
 * 1. ??  ? ?, ?? . 2. ??    ?? .
 * 
 * @throws Exception
 */
public static boolean initSystem() throws Exception {

    // move to driver file
    if (!TadpoleApplicationContextManager.isSystemInitialize())
        initJDBCDriver();

    // Is SQLite?
    if (!ApplicationArgumentUtils.isDBServer()) {
        if (!new File(DEFAULT_DB_FILE_LOCATION + DB_NAME).exists()) {
            if (logger.isInfoEnabled())
                logger.info("Createion Engine DB. Type is SQLite.");
            ClassLoader classLoader = TadpoleSystemInitializer.class.getClassLoader();
            InputStream is = classLoader
                    .getResourceAsStream("com/hangum/tadpole/engine/initialize/TadpoleEngineDBEngine.sqlite");

            byte[] dataByte = new byte[1024];
            int len = 0;

            FileOutputStream fos = new FileOutputStream(DEFAULT_DB_FILE_LOCATION + DB_NAME);
            while ((len = is.read(dataByte)) > 0) {
                fos.write(dataByte, 0, len);
            }

            fos.close();
            is.close();
        }
    }

    return TadpoleApplicationContextManager.getSystemAdmin() == null ? false : true;
}

From source file:com.enonic.esl.io.FileUtil.java

private static void inflateFile(File dir, InputStream is, ZipEntry entry) throws IOException {
    String entryName = entry.getName();
    File f = new File(dir, entryName);

    if (entryName.endsWith("/")) {
        f.mkdirs();//from  w w w.  j  av  a2  s . c o m
    } else {
        File parentDir = f.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(f);
            byte[] buffer = new byte[BUF_SIZE];
            for (int n = 0; (n = is.read(buffer)) > 0;) {
                os.write(buffer, 0, n);
            }
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
}

From source file:com.littcore.io.util.ZipUtils.java

public static void unzip(File srcZipFile, File targetFilePath, boolean isDelSrcFile) throws IOException {
    if (!targetFilePath.exists()) //?
        targetFilePath.mkdirs();//  ww w.ja  va 2  s.co  m
    ZipFile zipFile = new ZipFile(srcZipFile);

    Enumeration fileList = zipFile.getEntries();
    ZipEntry zipEntry = null;
    while (fileList.hasMoreElements()) {
        zipEntry = (ZipEntry) fileList.nextElement();
        if (zipEntry.isDirectory()) //?
        {
            File subFile = new File(targetFilePath, zipEntry.getName());
            if (!subFile.exists()) //??
                subFile.mkdir();
            continue;
        } else //?
        {
            File targetFile = new File(targetFilePath, zipEntry.getName());
            if (logger.isDebugEnabled()) {
                logger.debug("" + targetFile.getName());
            }

            if (!targetFile.exists()) {
                File parentPath = new File(targetFile.getParent());
                if (!parentPath.exists()) //????????
                    parentPath.mkdirs();
                //targetFile.createNewFile();
            }

            InputStream in = zipFile.getInputStream(zipEntry);
            FileOutputStream out = new FileOutputStream(targetFile);
            int len;
            byte[] buf = new byte[BUFFERED_SIZE];
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            in.close();
        }
    }
    zipFile.close();
    if (isDelSrcFile) {
        boolean isDeleted = srcZipFile.delete();
        if (isDeleted) {
            if (logger.isDebugEnabled()) {
                logger.debug("");
            }
        }
    }
}