List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:com.att.voice.TTS.java
public void say(String text, String file) { text = text.replace("\"", ""); try {//from w w w. jav a 2 s . c o m HttpPost httpPost = new HttpPost("https://api.att.com/speech/v3/textToSpeech"); httpPost.setHeader("Authorization", "Bearer " + mAuthToken); httpPost.setHeader("Accept", "audio/x-wav"); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setHeader("Tempo", "-16"); HttpEntity entity = new StringEntity(text, "UTF-8"); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); //String result = EntityUtils.toString(response.getEntity()); HttpEntity result = response.getEntity(); BufferedInputStream bis = new BufferedInputStream(result.getContent()); String filePath = System.getProperty("user.dir") + tempFile; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); executeOnCommandLine("afplay " + System.getProperty("user.dir") + "/" + tempFile); } catch (Exception ex) { System.err.println(ex.getMessage()); } }
From source file:com.yihaodian.performance.UploadReportMojo.java
@Override public void execute() throws MojoExecutionException { File file = new File("target/perf4junit/report.xml"); FileInputStream fis;// w w w . ja v a 2 s .c o m BufferedInputStream bis; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); HttpClient httpclient = new DefaultHttpClient(); HttpPost http = new HttpPost(endPoint); http.setEntity(new InputStreamEntity(bis, file.length())); HttpResponse response = httpclient.execute(http); getLog().info(endPoint); bis.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
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 w w 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:com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java
private byte[] getImageByteArray(String path) { Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering getImageByteArray()"); File file = new File(path); int size = (int) file.length(); byte[] bytes = new byte[size]; BufferedInputStream buf; try {/* w ww.jav a 2 s . co m*/ buf = new BufferedInputStream(new FileInputStream(file)); buf.read(bytes, 0, bytes.length); buf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting getImageByteArray()"); return bytes; }
From source file:de.nrw.hbz.deepzoomer.fileUtil.FileUtil.java
/** * <p><em>Title: Create a temporary File from a file identified by URL</em></p> * <p>Description: Method creates a temporary file from a remote file addressed * an by URL representing the orginal PDF, that should be converted</p> * // w ww. j a v a 2 s. c o m * @param fileName * @param url * @return */ public static String saveUrlToFile(String fileName, String url) { File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName); log.debug(inputFile.getAbsolutePath()); InputStream is = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; FileOutputStream fos = null; log.info(url); try { URL inputDocument = new URL(url); is = inputDocument.openStream(); bis = new BufferedInputStream(is); fos = new FileOutputStream(inputFile); bos = new BufferedOutputStream(fos); int i = -1; while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); } catch (Exception e) { log.error(e); } finally { if (bos != null) { try { bos.close(); } catch (IOException ioExc) { log.error(ioExc); } } if (fos != null) { try { fos.close(); } catch (IOException ioExc) { log.error(ioExc); } } if (bis != null) { try { bis.close(); } catch (IOException ioExc) { log.error(ioExc); } } if (is != null) { try { is.close(); } catch (IOException ioExc) { log.error(ioExc); } } } return inputFile.getName(); }
From source file:com.dotcms.publisher.myTest.PushPublisher.java
/** * Does the work of compression and going recursive for nested directories * <p/>//w ww . j a va 2 s . c om * * * @param taos The archive * @param file The file to add to the archive * @param dir The directory that should serve as the parent directory in the archivew * @throws IOException */ private void addFilesToCompression(TarArchiveOutputStream taos, File file, String dir, String bundleRoot) throws IOException { if (!file.isHidden()) { // Create an entry for the file if (!dir.equals(".")) taos.putArchiveEntry(new TarArchiveEntry(file, dir + File.separator + file.getName())); if (file.isFile()) { // Add the file to the archive BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(new FileInputStream(file), taos); taos.closeArchiveEntry(); bis.close(); } else if (file.isDirectory()) { //Logger.info(this.getClass(),file.getPath().substring(bundleRoot.length())); // close the archive entry if (!dir.equals(".")) taos.closeArchiveEntry(); // go through all the files in the directory and using recursion, add them to the archive for (File childFile : file.listFiles()) { addFilesToCompression(taos, childFile, file.getPath().substring(bundleRoot.length()), bundleRoot); } } } }
From source file:com.volley.air.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*w w w . jav a2s . co m*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) { MultiPartParam param = entry.getValue(); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (Entry<String, String> entry : filesToUpload.entrySet()) { File file = new File(entry.getValue()); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, entry.getKey(), file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.mb.framework.util.property.PropertyUtilExt.java
/** * Copy property values from the origin bean to the destination bean for all * cases where the property names are the same. For each property, a * conversion is attempted as necessary. All combinations of standard * JavaBeans and DynaBeans as origin and destination are supported. * Properties that exist in the origin bean, but do not exist in the * destination bean (or are read-only in the destination bean) are silently * ignored./*from w w w .j av a 2 s. c om*/ * <p> * In addition to the method with the same name in the * <code>org.apache.commons.beanutils.PropertyUtils</code> class this method * can also copy properties of the following types: * <ul> * <li>java.lang.Integer</li> * <li>java.lang.Double</li> * <li>java.lang.Long</li> * <li>java.lang.Short</li> * <li>java.lang.Float</li> * <li>java.lang.String</li> * <li>java.lang.Boolean</li> * <li>java.sql.Date</li> * <li>java.sql.Time</li> * <li>java.sql.Timestamp</li> * <li>java.math.BigDecimal</li> * <li>a container-managed relations field.</li> * </ul> * * @param dest * Destination bean whose properties are modified * @param orig * Origin bean whose properties are retrieved * @throws IllegalAccessException * if the caller does not have access to the property accessor * method * @throws InvocationTargetException * if the property accessor method throws an exception * @throws NoSuchMethodException * if an accessor method for this propety cannot be found * @throws ClassNotFoundException * if an incorrect relations class mapping exists. * @throws InstantiationException * if an object of the mapped relations class can not be * constructed. */ public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, Exception { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (PropertyUtils.getPropertyDescriptor(dest, name) != null) { Object origValue = PropertyUtils.getSimpleProperty(orig, name); String origParamType = origDescriptors[i].getPropertyType().getName(); try { // edited // if (origValue == null)throw new NullPointerException(); PropertyUtils.setSimpleProperty(dest, name, origValue); } catch (Exception e) { try { String destParamType = PropertyUtils.getPropertyType(dest, name).getName(); if (origValue instanceof String) { if (destParamType.equals("java.lang.Integer")) { Integer intValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { intValue = new Integer(sValue); } PropertyUtils.setSimpleProperty(dest, name, intValue); } else if (destParamType.equals("java.lang.Byte")) { Byte byteValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { byteValue = new Byte(sValue); } PropertyUtils.setSimpleProperty(dest, name, byteValue); } else if (destParamType.equals("java.lang.Double")) { Double doubleValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { doubleValue = new Double(sValue); } PropertyUtils.setSimpleProperty(dest, name, doubleValue); } else if (destParamType.equals("java.lang.Long")) { Long longValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { longValue = new Long(sValue); } PropertyUtils.setSimpleProperty(dest, name, longValue); } else if (destParamType.equals("java.lang.Short")) { Short shortValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { shortValue = new Short(sValue); } PropertyUtils.setSimpleProperty(dest, name, shortValue); } else if (destParamType.equals("java.lang.Float")) { Float floatValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { floatValue = new Float(sValue); } PropertyUtils.setSimpleProperty(dest, name, floatValue); } else if (destParamType.equals("java.sql.Date")) { java.sql.Date dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Date(DATE_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.sql.Time")) { java.sql.Time dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Time(TIME_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.sql.Timestamp")) { java.sql.Timestamp dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Timestamp(TIMESTAMP_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.lang.Boolean")) { Boolean bValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { bValue = Boolean.valueOf(sValue); } PropertyUtils.setSimpleProperty(dest, name, bValue); } else if (destParamType.equals("java.math.BigDecimal")) { BigDecimal bdValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { bdValue = new BigDecimal(sValue); } PropertyUtils.setSimpleProperty(dest, name, bdValue); } } else if ((origValue != null) && (destParamType.equals("java.lang.String"))) { // we're transferring a business-layer value object // into a String-based Struts form bean.. if ("java.sql.Date".equals(origParamType)) { PropertyUtils.setSimpleProperty(dest, name, DATE_FORMATTER.format(origValue)); } else if ("java.sql.Timestamp".equals(origParamType)) { PropertyUtils.setSimpleProperty(dest, name, TIMESTAMP_FORMATTER.format(origValue)); } else if ("java.sql.Blob".equals(origParamType)) { // convert a Blob to a String.. Blob blob = (Blob) origValue; BufferedInputStream bin = null; try { int bytesRead; StringBuffer result = new StringBuffer(); byte[] buffer = new byte[READ_BUFFER_LENGTH]; bin = new BufferedInputStream(blob.getBinaryStream()); do { bytesRead = bin.read(buffer); if (bytesRead != -1) { result.append(new String(buffer, 0, bytesRead)); } } while (bytesRead == READ_BUFFER_LENGTH); PropertyUtils.setSimpleProperty(dest, name, result.toString()); } finally { if (bin != null) try { bin.close(); } catch (IOException ignored) { } } } else { PropertyUtils.setSimpleProperty(dest, name, origValue.toString()); } } } catch (Exception e2) { throw e2; } } } } }
From source file:edu.usf.cutr.manager.IOManagerImpl.java
@Override public void downloadFile(String url, String path) throws MalformedURLException, IOException { BufferedInputStream in = null; FileOutputStream fout = null; try {/*from w w w . j a v a 2 s.c om*/ in = new BufferedInputStream(new URL(url).openStream()); fout = new FileOutputStream(path); final byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } }
From source file:com.androidex.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*from w w w . ja v a 2 s . c o m*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }