Example usage for java.io OutputStream close

List of usage examples for java.io OutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:com.canoo.webtest.boundary.StreamBoundary.java

/**
 * Close an OutputStream and abort step if an error occur.
 *
 * Wraps IOException's./*from   w ww.  j  ava2  s  .  c o m*/
 *
 * @param os
 * @param step
 */
public static void tryCloseOutputStream(final OutputStream os, final Step step) {
    if (os != null) {
        try {
            os.close();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new StepExecutionException("Error closing stream: " + e.getMessage(), step);
        }
    }
}

From source file:Main.java

public static void saveImage(String imageUrl, String destinationFile) throws Exception {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;//w w  w  .java  2s.  c om

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {/* w w w  .j a v a2 s.  c  o  m*/
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:Main.java

static final File createFile(File file, String data) {
    OutputStream os = null;
    try {/* ww  w . j  a  v  a 2s.  c om*/
        os = new FileOutputStream(file);
        os.write(data.getBytes());
        os.flush();
        os.close();
        return file;
    } catch (Exception e) {
        try {
            if (null != os) {
                os.close();
            }
        } catch (Exception e2) {
        }
        toast("Cannot write the data to file " + file.getAbsolutePath() + ": " + e.getMessage());
    }

    return null;
}

From source file:Utils.java

/**
 * Unpack an archive from a URL//www  . j  a va  2  s . c  o  m
 * 
 * @param url
 * @param targetDir
 * @return the file to the url
 * @throws IOException
 */
public static File unpackArchive(URL url, File targetDir) throws IOException {
    if (!targetDir.exists()) {
        targetDir.mkdirs();
    }
    InputStream in = new BufferedInputStream(url.openStream(), 1024);
    // make sure we get the actual file
    File zip = File.createTempFile("arc", ".zip", targetDir);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(zip));
    copyInputStream(in, out);
    out.close();
    return unpackArchive(zip, targetDir);
}

From source file:com.qq.tars.tools.SystemUtils.java

public static Pair<Integer, Pair<String, String>> exec(String command) {
    log.info("start to exec shell, command={}", command);

    try {//from   ww w .j  av a2  s. co  m
        Process process = Runtime.getRuntime().exec("/bin/sh");

        OutputStream os = process.getOutputStream();
        os.write(command.getBytes());
        os.close();

        final StringBuilder stdout = new StringBuilder(1024);
        final StringBuilder stderr = new StringBuilder(1024);
        final BufferedReader stdoutReader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(process.getErrorStream(), "GBK"));

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stdoutReader.readLine())) {
                    stdout.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stdout error", e);
            }
        }).start();

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stderrReader.readLine())) {
                    stderr.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stderr error", e);
            }
        }).start();

        int ret = process.waitFor();

        stdoutReader.close();
        stderrReader.close();

        Pair<String, String> output = Pair.of(stdout.toString(), stderr.toString());
        return Pair.of(ret, output);
    } catch (Exception e) {
        return Pair.of(-1, Pair.of("", ExceptionUtils.getStackTrace(e)));
    }
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//*from   ww  w  .  j  ava 2s .  c o  m*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:Main.java

private static void post(String endpoint, Map<String, String> params) throws IOException {

    URL url;// w w  w . java2  s . c  om
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Map.Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:de.ingrid.interfaces.csw.admin.command.AdminManager.java

/**
 * Read the override configuration and write a new bcrypt-hash password.
 *//*w  ww  .ja  v a  2s  .co m*/
private static void resetPassword(String newPassword) {
    try {
        InputStream is = new FileInputStream("conf/config.override.properties");
        Properties props = new Properties();
        props.load(is);
        props.setProperty("ingrid.admin.password", BCrypt.hashpw(newPassword, BCrypt.gensalt()));

        OutputStream os = new FileOutputStream("conf/config.override.properties");
        props.store(os, "Override configuration written by the application");
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.alexholmes.hadooputils.io.FileUtils.java

/**
 * Writes the array list into a file as newline-separated lines.
 *
 * @param fs a Hadoop file system//from  w  w w . j ava2  s .c om
 * @param p  the file path
 * @return array of lines to write to the file
 * @throws java.io.IOException if something goes wrong
 */
public static void writeLines(Collection<?> lines, final FileSystem fs, final Path p) throws IOException {
    OutputStream stream = fs.create(p);
    try {
        IOUtils.writeLines(lines, IOUtils.LINE_SEPARATOR, stream);
    } finally {
        stream.close();
    }
}