List of usage examples for java.io OutputStream close
public void close() throws IOException
From source file:com.wx.kernel.util.HttpKit.java
/** * Send POST request/*from w ww .jav a 2s . co m*/ */ public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(data.getBytes(CHARSET)); out.flush(); out.close(); return readResponseString(conn); } catch (Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:Main.java
public static String executePost(String targetURL, String urlParameters) { try {//ww w . jav a 2 s. c o m HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); //connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream output = null; try { output = connection.getOutputStream(); output.write(urlParameters.getBytes()); } finally { if (output != null) try { output.flush(); output.close(); } catch (IOException logOrIgnore) { } } InputStream response = connection.getInputStream(); String contentType = connection.getHeaderField("Content-Type"); String responseStr = ""; if (true) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response)); for (String line; (line = reader.readLine()) != null;) { //System.out.println(line); responseStr = responseStr + line; Thread.sleep(2); } } finally { if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) { } } } else { // It's likely binary content, use InputStream/OutputStream. System.out.println("Binary content"); } return responseStr; } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:Main.java
private static boolean copyAsset(AssetManager assetManager, String fromAssetPath, String toPath) { InputStream in = null;//from w w w .ja v a 2 s . c o m OutputStream out = null; try { in = assetManager.open(fromAssetPath); new File(toPath).createNewFile(); out = new FileOutputStream(toPath); copyFile2(in, out); in.close(); in = null; out.flush(); out.close(); out = null; return true; } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:FileHelper.java
/** * Move a file from one location to another. An attempt is made to rename * the file and if that fails, the file is copied and the old file deleted. * * @param from file which should be moved. * @param to desired destination of the file. * @param overwrite If false, an exception will be thrown rather than overwrite a file. * @throws IOException if an error occurs. * * @since ostermillerutils 1.00.00// w w w . j a v a 2 s.co m */ public static void move(File from, File to, boolean overwrite) throws IOException { if (to.exists()) { if (overwrite) { if (!to.delete()) { throw new IOException(MessageFormat.format(labels.getString("deleteerror"), (Object[]) new String[] { to.toString() })); } } else { throw new IOException(MessageFormat.format(labels.getString("alreadyexistserror"), (Object[]) new String[] { to.toString() })); } } if (from.renameTo(to)) return; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(from); out = new FileOutputStream(to); copy(in, out); in.close(); in = null; out.flush(); out.close(); out = null; if (!from.delete()) { throw new IOException(MessageFormat.format(labels.getString("deleteoriginalerror"), (Object[]) new String[] { from.toString(), to.toString() })); } } finally { if (in != null) { in.close(); in = null; } if (out != null) { out.flush(); out.close(); out = null; } } }
From source file:Main.java
private static void copyFiles(InputStream source, File dest) throws IOException { OutputStream output = null; int bytesRead = 0; byte[] buf = null; try {//from w w w . j ava 2 s . co m output = new FileOutputStream(dest); buf = new byte[1024]; while ((bytesRead = source.read(buf)) > 0) { output.write(buf, 0, bytesRead); } } finally { source.close(); output.close(); bytesRead = 0; output = null; source = null; buf = null; } }
From source file:org.apache.hadoop.gateway.GatewayLdapPosixGroupFuncTest.java
public static void setupGateway(int ldapPort) throws Exception { File targetDir = new File(System.getProperty("user.dir"), "target"); File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID()); gatewayDir.mkdirs();//from ww w . j ava 2 s .co m GatewayTestConfig testConfig = new GatewayTestConfig(); config = testConfig; testConfig.setGatewayHomeDir(gatewayDir.getAbsolutePath()); File topoDir = new File(testConfig.getGatewayTopologyDir()); topoDir.mkdirs(); File deployDir = new File(testConfig.getGatewayDeploymentDir()); deployDir.mkdirs(); DefaultGatewayServices srvcs = new DefaultGatewayServices(); Map<String, String> options = new HashMap<>(); options.put("persist-master", "true"); options.put("master", "hadoop"); try { srvcs.init(testConfig, options); } catch (ServiceLifecycleException e) { e.printStackTrace(); // I18N not required. } gateway = GatewayServer.startGateway(testConfig, srvcs); MatcherAssert.assertThat("Failed to start gateway.", gateway, notNullValue()); LOG.info("Gateway port = " + gateway.getAddresses()[0].getPort()); gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath(); clusterUrl = gatewayUrl + "/test-cluster"; serviceUrl = clusterUrl + "/test-service-path/test-service-resource"; GatewayServices services = GatewayServer.getGatewayServices(); AliasService aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE); aliasService.addAliasForCluster("test-cluster", "ldcSystemPassword", "guest-password"); char[] password1 = aliasService.getPasswordFromAliasForCluster("test-cluster", "ldcSystemPassword"); File descriptor = new File(topoDir, "test-cluster.xml"); OutputStream stream = new FileOutputStream(descriptor); createTopology(ldapPort).toStream(stream); stream.close(); }
From source file:com.cloudera.knittingboar.utils.Utils.java
/** * Untar an input file into an output file. * //from ww w . j a v a2 s . c om * The output file is created in the output folder, having the same name as * the input file, minus the '.tar' extension. * * @param inputFile * the input .tar file * @param outputDir * the output directory file. * @throws IOException * @throws FileNotFoundException * * @return The {@link List} of {@link File}s with the untared content. * @throws ArchiveException */ private static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException { System.out.println( String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath())); final List<File> untaredFiles = new LinkedList<File>(); final InputStream is = new FileInputStream(inputFile); final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream("tar", is); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { System.out.println( String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.exists()) { System.out.println(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.mkdirs()) { throw new IllegalStateException( String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { System.out.println(String.format("Creating output file %s.", outputFile.getAbsolutePath())); final OutputStream outputFileStream = new FileOutputStream(outputFile); IOUtils.copy(debInputStream, outputFileStream); outputFileStream.close(); } untaredFiles.add(outputFile); } debInputStream.close(); return untaredFiles; }
From source file:Main.java
public static void copy(File src, File dest) throws IOException { if (src.isDirectory()) { //if directory not exists, create it if (!dest.exists()) { dest.mkdir();/*from ww w. j a va 2 s .c om*/ System.out.println("Directory copied from " + src + " to " + dest); } //list all the directory contents String files[] = src.list(); for (int c = 0; c < files.length; c++) { //construct the src and dest file structure File srcFile = new File(src, files[c]); File destFile = new File(dest, files[c]); //recursive copy copy(srcFile, destFile); } } else { //if file, then copy it //Use bytes stream to support all file types InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); System.out.println("File copied from " + src + " to " + dest); } }
From source file:com.aurel.track.exchange.UploadHelper.java
/** * Upload the file in a person and type specific directory * @return/* w w w . ja v a 2 s . c om*/ */ public static String upload(File uploadFile, String uploadFileFileName, String targetPath, Locale locale, String successResult) { InputStream inputStream; try { inputStream = new FileInputStream(uploadFile); } catch (FileNotFoundException e) { LOGGER.error("Getting the input stream for the uploaded file failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(ServletActionContext.getResponse(), JSONUtility.encodeJSONFailure(LocalizeUtil .getLocalizedTextFromApplicationResources("admin.actions.importTp.err.failed", locale))); return null; } UploadHelper.ensureDir(targetPath); File targetFile = new File(targetPath, uploadFileFileName); if (targetFile.exists()) { //if the file exists (as a result of a previous import) then delete it targetFile.delete(); } try { OutputStream outputStream = new FileOutputStream(targetFile); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } inputStream.close(); outputStream.close(); } catch (Exception e) { LOGGER.error("Saving the file " + uploadFileFileName + " to the temporary directory " + targetPath + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(ServletActionContext.getResponse(), JSONUtility.encodeJSONFailure(LocalizeUtil .getLocalizedTextFromApplicationResources("admin.actions.importTp.err.failed", locale))); return null; } return successResult; }
From source file:Main.java
/** * Compresses a GZIP file./*from w ww .j av a 2s. co m*/ * * @param bytes * The uncompressed bytes. * @return The compressed bytes. * @throws IOException * if an I/O error occurs. */ public static byte[] gzip(byte[] bytes) throws IOException { /* create the streams */ InputStream is = new ByteArrayInputStream(bytes); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream os = new GZIPOutputStream(bout); try { /* copy data between the streams */ byte[] buf = new byte[4096]; int len = 0; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } finally { os.close(); } /* return the compressed bytes */ return bout.toByteArray(); } finally { is.close(); } }