Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

In this page you can find the example usage for java.io BufferedOutputStream close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java

public void unpackBundleTarToFS(String bundle_path, File fs_path) {
    URL url = fBundle.getEntry(bundle_path);
    TestCase.assertNotNull(url);/*from   ww w.j  a v a2s. c o m*/

    if (!fs_path.isDirectory()) {
        TestCase.assertTrue(fs_path.mkdirs());
    }
    InputStream in = null;
    TarArchiveInputStream tar_stream = null;

    try {
        in = url.openStream();
    } catch (IOException e) {
        TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage());
    }

    tar_stream = new TarArchiveInputStream(in);

    try {
        byte tmp[] = new byte[4 * 1024];
        int cnt;

        ArchiveEntry te;

        while ((te = tar_stream.getNextEntry()) != null) {
            // System.out.println("Entry: \"" + ze.getName() + "\"");
            File entry_f = new File(fs_path, te.getName());
            if (te.getName().endsWith("/")) {
                // Directory
                continue;
            }
            if (!entry_f.getParentFile().exists()) {
                TestCase.assertTrue(entry_f.getParentFile().mkdirs());
            }
            FileOutputStream fos = new FileOutputStream(entry_f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length);

            while ((cnt = tar_stream.read(tmp, 0, tmp.length)) > 0) {
                bos.write(tmp, 0, cnt);
            }
            bos.flush();
            bos.close();
            fos.close();

            //            tar_stream.closeEntry();
        }
        tar_stream.close();
    } catch (IOException e) {
        e.printStackTrace();
        TestCase.fail("Failed to unpack tar file: " + e.getMessage());
    }
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.bpmai.BpmaiImporter.java

/**
 * Reads the given content and writes it into a  file with the given path.
 * @param in stream to read/*from   w  w w .  j a va  2 s.  c o  m*/
 * @param targetPath path to write the read content to
 * @throws IOException if the specified path does not exists.
 */
private void copyInputStream(InputStream in, String targetPath) throws IOException {
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetPath));
    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) >= 0) {
        bufferedOutputStream.write(buffer, 0, len);
    }
    in.close();
    bufferedOutputStream.close();
}

From source file:com.piaoyou.util.FileUtil.java

public static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException {

    File srcFile = new File(srcFilename);
    if (!srcFile.exists()) {
        throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
    }/*from   w  w  w.  ja  v  a 2  s  . c om*/
    if (!srcFile.canRead()) {
        throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
    }

    File destFile = new File(destFilename);
    if (overwrite == false) {
        if (destFile.exists()) {
            return;
        }
    } else {
        if (destFile.exists()) {
            if (!destFile.canWrite()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        } else {
            if (!destFile.createNewFile()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        }
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {
        inputStream = new BufferedInputStream(new FileInputStream(srcFile));
        outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java

public void unpackBundleTgzToFS(String bundle_path, File fs_path) {
    URL url = fBundle.getEntry(bundle_path);
    TestCase.assertNotNull(url);/*from  ww  w  . java  2s .c om*/

    if (!fs_path.isDirectory()) {
        TestCase.assertTrue(fs_path.mkdirs());
    }
    InputStream in = null;
    GzipCompressorInputStream gz_stream = null;
    TarArchiveInputStream tar_stream = null;

    try {
        in = url.openStream();
    } catch (IOException e) {
        TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage());
    }

    try {
        gz_stream = new GzipCompressorInputStream(in);
    } catch (IOException e) {
        TestCase.fail("Failed to uncompress data file " + bundle_path + " : " + e.getMessage());
    }

    tar_stream = new TarArchiveInputStream(gz_stream);

    try {
        byte tmp[] = new byte[4 * 1024];
        int cnt;

        ArchiveEntry te;

        while ((te = tar_stream.getNextEntry()) != null) {
            // System.out.println("Entry: \"" + ze.getName() + "\"");
            File entry_f = new File(fs_path, te.getName());
            if (te.getName().endsWith("/")) {
                // Directory
                continue;
            }
            if (!entry_f.getParentFile().exists()) {
                TestCase.assertTrue(entry_f.getParentFile().mkdirs());
            }
            FileOutputStream fos = new FileOutputStream(entry_f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length);

            while ((cnt = tar_stream.read(tmp, 0, tmp.length)) > 0) {
                bos.write(tmp, 0, cnt);
            }
            bos.flush();
            bos.close();
            fos.close();

            //            tar_stream.closeEntry();
        }
        tar_stream.close();
    } catch (IOException e) {
        e.printStackTrace();
        TestCase.fail("Failed to unpack tar file: " + e.getMessage());
    }
}

From source file:osh.comdriver.simulation.cruisecontrol.ScheduleDrawer.java

public void refreshDiagram(List<Schedule> schedules, HashMap<VirtualCommodity, PriceSignal> ps,
        HashMap<VirtualCommodity, PowerLimitSignal> pls, long time, boolean saveGraph) {

    JFreeChart chart = createStuffForPanel(schedules, ps, pls, time);

    if (!saveGraph) {
        panel.setChart(chart);//  w ww.  j ava  2s . com
    } else {
        BufferedOutputStream out;
        try {
            out = new BufferedOutputStream(new FileOutputStream("logs/graphic_" + counter + ".png"));
            ChartUtilities.writeChartAsPNG(out, chart, 1024, 768);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        counter++;
    }

}

From source file:net.okjsp.imageloader.ImageFetcher.java

/**
 * Download a bitmap from a URL, write it to a disk and return the File pointer. This
 * implementation uses a simple disk cache.
 *
 * @param context The context to use//from   w  w w .j a  v  a 2  s  . co m
 * @param urlString The URL to fetch
 * @return A File pointing to the fetched bitmap
 */
public static File downloadBitmap(Context context, String urlString) {
    final File cacheDir = DiskLruCache.getDiskCacheDir(context, HTTP_CACHE_DIR);

    final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir, HTTP_CACHE_SIZE);

    final File cacheFile = new File(cache.createFilePath(urlString));

    if (cache.containsKey(urlString)) {
        if (BuildConfig.DEBUG && DEBUG_LOG) {
            Log.d(TAG, "downloadBitmap - found in http cache - " + urlString);
        }
        return cacheFile;
    }

    if (BuildConfig.DEBUG && DEBUG_LOG) {
        Log.d(TAG, "downloadBitmap - downloading - " + urlString);
    }

    ImageLoaderUtils.disableConnectionReuseIfNecessary();
    BufferedOutputStream out = null;
    InputStream in = null;
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(urlString);

    try {
        if (DEBUG_LOG)
            Log.d(TAG, "getRequest:" + getRequest.toString());
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            in = new BufferedInputStream(entity.getContent(), ImageLoaderUtils.IO_BUFFER_SIZE);
        }
        out = new BufferedOutputStream(new FileOutputStream(cacheFile), ImageLoaderUtils.IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }

        in.close();
        in = null;

        return cacheFile;

    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            in = null;
        }

        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.piaoyou.util.FileUtil.java

public static void copyFile(InputStream inputStream1, OutputStream outputStream1) throws IOException {

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {/*from   ww  w .  j a  v a  2  s  .  c  o  m*/
        inputStream = new BufferedInputStream(inputStream1);
        outputStream = new BufferedOutputStream(outputStream1);
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:mamo.vanillaVotifier.JsonConfig.java

@Override
public synchronized void load() throws IOException, InvalidKeySpecException {
    if (!configFile.exists()) {
        BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
        StringBuilder stringBuilder = new StringBuilder();
        int i;//from  w  ww.j a  v  a2s. c o m
        while ((i = in.read()) != -1) {
            stringBuilder.append((char) i);
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
        for (char c : stringBuilder.toString()
                .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
                        System.getProperty("line.separator"))
                .toCharArray()) {
            out.write((int) c);
        }
        out.flush();
        out.close();
    }
    BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
    JSONObject defaultConfig = new JSONObject(new JSONTokener(in));
    in.close();
    JSONObject config = new JSONObject(
            new JSONTokener(new BufferedInputStream(new FileInputStream(configFile))));
    boolean save = JsonUtils.merge(defaultConfig, config);
    configVersion = config.getInt("config-version");
    if (configVersion == 2) {
        v2ToV3(config);
        configVersion = 3;
        save = true;
    }
    logFile = new File(config.getString("log-file"));
    inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port"));
    publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public"));
    privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private"));
    if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
        KeyPair keyPair = RsaUtils.genKeyPair();
        PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile)));
        publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
        publicPemWriter.flush();
        publicPemWriter.close();
        PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile)));
        privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded()));
        privatePemWriter.flush();
        privatePemWriter.close();
    }
    if (!publicKeyFile.exists()) {
        throw new PublicKeyFileNotFoundException();
    }
    if (!privateKeyFile.exists()) {
        throw new PrivateKeyFileNotFoundException();
    }
    PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile)));
    PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile)));
    PemObject publicPemObject = publicKeyPemReader.readPemObject();
    if (publicPemObject == null) {
        throw new InvalidPublicKeyFileException();
    }
    PemObject privatePemObject = privateKeyPemReader.readPemObject();
    if (privatePemObject == null) {
        throw new InvalidPrivateKeyFileException();
    }
    keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()),
            RsaUtils.bytesToPrivateKey(privatePemObject.getContent()));
    publicKeyPemReader.close();
    privateKeyPemReader.close();
    rconConfigs = new ArrayList<RconConfig>();
    for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) {
        JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i);
        RconConfig rconConfig = new RconConfig(
                new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")),
                jsonObject.getString("password"));
        for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) {
            rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j));
        }
        rconConfigs.add(rconConfig);
    }
    loaded = true;
    if (save) {
        save();
    }
}

From source file:au.org.ala.layers.util.BatchConsumer.java

@Override
public void run() {
    boolean repeat = true;
    String id = "";

    while (repeat) {
        String currentBatch = null;
        try {/* w  ww . java 2 s  .c o  m*/
            currentBatch = waitingBatchDirs.take();

            id = new File(currentBatch).getName();

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm:ss:SSS");
            String str = sdf.format(new Date());
            BatchProducer.logUpdateEntry(id, "started", "started", str, null);
            writeToFile(currentBatch + "status.txt", "started at " + str, true);
            writeToFile(currentBatch + "started.txt", str, true);

            String fids = readFile(currentBatch + "fids.txt");
            String points = readFile(currentBatch + "points.txt");
            String gridcache = readFile(currentBatch + "gridcache.txt");

            ArrayList<String> sample = null;

            HashMap[] pointSamples = null;
            if ("1".equals(gridcache)) {
                pointSamples = layerIntersectDao.sampling(points, 1);
            } else if ("2".equals(gridcache)) {
                pointSamples = layerIntersectDao.sampling(points, 2);
            } else {
                IntersectCallback callback = new ConsumerCallback(id);
                sample = layerIntersectDao.sampling(fids.split(","), splitStringToDoublesArray(points, ','),
                        callback);
            }

            //convert pointSamples to string array
            if (pointSamples != null) {
                Set columns = new LinkedHashSet();
                for (int i = 0; i < pointSamples.length; i++) {
                    columns.addAll(pointSamples[i].keySet());
                }

                //fids
                fids = "";
                for (Object o : columns) {
                    if (!fids.isEmpty()) {
                        fids += ",";
                    }
                    fids += o;
                }

                //columns
                ArrayList<StringBuilder> sb = new ArrayList<StringBuilder>();
                for (int i = 0; i < columns.size(); i++) {
                    sb.add(new StringBuilder());
                }
                for (int i = 0; i < pointSamples.length; i++) {
                    int pos = 0;
                    for (Object o : columns) {
                        sb.get(pos).append("\n").append(pointSamples[i].get(o));
                        pos++;
                    }
                }

                //format
                sample = new ArrayList<String>();
                for (int i = 0; i < sb.size(); i++) {
                    sample.add(sb.get(i).toString());
                }
            }

            System.out.println("start csv output at " + sdf.format(new Date()));
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(currentBatch + "sample.csv"));
            IntersectUtil.writeSampleToStream(splitString(fids, ','), splitString(points, ','), sample, bos);
            bos.flush();
            bos.close();
            System.out.println("finish csv output at " + sdf.format(new Date()));

            str = sdf.format(new Date());
            BatchProducer.logUpdateEntry(id, "finished", "finished", str, fids.split(",").length + 1);
            writeToFile(currentBatch + "status.txt", "finished at " + str, true);
            writeToFile(currentBatch + "finished.txt", str, true);

        } catch (InterruptedException e) {
            //thread stop request
            repeat = false;
            break;
        } catch (Exception e) {
            if (currentBatch != null) {
                try {
                    BatchProducer.logUpdateEntry(id, "error", "error", e.getMessage(), null);
                    writeToFile(currentBatch + "status.txt", "error " + e.getMessage(), true);
                    writeToFile(currentBatch + "error.txt", e.getMessage(), true);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }

        currentBatch = null;
    }
}

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

/**
  * Este mtodo guarda la configuracin en el fichero SignXML.properties
  * @throws IOException /*from   w ww  . ja  v  a 2s .com*/
  */
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();

}