List of usage examples for java.io FileOutputStream flush
public void flush() throws IOException
From source file:Main.java
/** * Reads a file that is embedded in our application and writes it to the device storage * @param context/*from ww w.j a v a2 s . c om*/ * @param file * @param assetFileDescriptor */ private static void saveFileToDevice(Context context, File file, AssetFileDescriptor assetFileDescriptor) { // The output stream is used to write the new file to the device storage FileOutputStream outputStream = null; // The input stream is used for reading the file that is embedded in our application FileInputStream inputStream = null; try { byte[] buffer = new byte[1024]; // Create the input stream inputStream = (assetFileDescriptor != null) ? assetFileDescriptor.createInputStream() : null; // Create the output stream outputStream = new FileOutputStream(file, false); // Read the file into buffer int i = (inputStream != null) ? inputStream.read(buffer) : 0; // Continue writing and reading the file until we reach the end while (i != -1) { outputStream.write(buffer, 0, i); i = (inputStream != null) ? inputStream.read(buffer) : 0; } outputStream.flush(); } catch (IOException io) { // Display a message to the user Toast toast = Toast.makeText(context, "Could not save the file", Toast.LENGTH_SHORT); toast.show(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { // We should really never get this far, but we might consider adding a // warning/log entry here... } } if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { // We should really never get this far, but we might consider adding a // warning/log entry here... } } } }
From source file:com.kactech.otj.Utils.java
public static void writeDirs(File file, byte[] content) throws IOException { file.getParentFile().mkdirs();/*from w ww.j a va 2s . com*/ if (!file.getParentFile().exists()) throw new IllegalStateException("parent directory not exist"); FileOutputStream fos = new FileOutputStream(file); fos.write(content); fos.flush(); fos.close(); }
From source file:com.baobao121.baby.common.SimpleUploaderServlet.java
public static void changeDimension(InputStream bis, FileOutputStream desc, int w, int h) throws IOException { Image src = javax.imageio.ImageIO.read(bis); // Image int width = src.getWidth(null); // ? int height = src.getHeight(null); // ? if (width <= w && height <= h) { BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, width, height, null); // ?? JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc); encoder.encode(tag);/* w ww . j a v a 2s .c om*/ desc.flush(); desc.close(); bis.close(); } else { if (width != height) { if (w * height < h * width) { h = (int) (height * w / width); } else { w = (int) (width * h / height); } } BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, w, h, null); // ?? JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc); encoder.encode(tag); desc.flush(); desc.close(); bis.close(); } // JPEG? }
From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java
/** * @param inputStream// ww w .j ava2 s. c om * @param tmpFile * @throws IOException */ public static void storeStreamInFile(InputStream in, File f) throws IOException { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); byte[] b = new byte[1024]; int read_size; while ((read_size = in.read(b)) != -1) { fos.write(b, 0, read_size); fos.flush(); } fos.close(); }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
/** * download file url and save it//from w ww . j a v a2s.c o m * * @param url */ public static String downloadFile(String url) { int BYTE_ARRAY_SIZE = 1024; int CONNECTION_TIMEOUT = 30000; int READ_TIMEOUT = 30000; // downloading cover image and saving it into file try { URL imageUrl = new URL(URLDecoder.decode(url)); URLConnection conn = imageUrl.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); File resFile = new File( Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.Utils.md5(url)); if (!resFile.exists()) { resFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(resFile); int current = 0; byte[] buf = new byte[BYTE_ARRAY_SIZE]; Arrays.fill(buf, (byte) 0); while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) { fos.write(buf, 0, current); Arrays.fill(buf, (byte) 0); } bis.close(); fos.flush(); fos.close(); Log.d("", ""); return resFile.getAbsolutePath(); } catch (SocketTimeoutException e) { return null; } catch (IllegalArgumentException e) { return null; } catch (Exception e) { return null; } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends an HTTP GET request to a url/*from w w w. j a v a 2 s .co m*/ * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user * @param password * @return the file written. * @throws Exception */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); } return file; }
From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java
/** * content// w w w.jav a 2s . c o m * * @param file * ? * @param content * * @param code * ?? */ public static boolean writeFile(File file, byte[] content) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "writeFile", "[file:" + file + "][content:" + content + "]")); boolean result = false; if (file == null || content == null || content.length == 0) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FILEPROCESS_ERROR, "Can not process empty file or content: " + "[file:" + file + "][content:" + content + "]")); return result; } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); // fileOutputStream.write(content); fileOutputStream.flush(); result = true; } catch (IOException e) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FILEPROCESS_ERROR, "IOException")); LOGGER.error(e.getMessage(), e); return false; } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FILEPROCESS_ERROR, "IOException")); LOGGER.error(e.getMessage(), e); return false; } } } LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "writeFile", "[file:" + file + "][content:" + content + "]")); return result; }
From source file:apim.restful.exportimport.utils.APIImportUtil.java
/** * This method uploads a given file to specified location * * @param uploadedInputStream input stream of the file * @param newFileName name of the file to be created * @param storageLocation destination of the new file *//*from w ww .j a v a 2 s. c om*/ public static void transferFile(InputStream uploadedInputStream, String newFileName, String storageLocation) throws APIManagementException { FileOutputStream outFileStream = null; try { outFileStream = new FileOutputStream(new File(storageLocation, newFileName)); int read = 0; byte[] bytes = new byte[1024]; while ((read = uploadedInputStream.read(bytes)) != -1) { outFileStream.write(bytes, 0, read); } } catch (IOException e) { log.error("Error in transferring files."); throw new APIManagementException("Error in transferring files.", e); } finally { try { if (outFileStream != null) { outFileStream.flush(); outFileStream.close(); } } catch (IOException e) { log.error("Error in closing output streams while transferring files."); } } }
From source file:com.ai.runner.center.pay.web.business.payment.util.third.unionpay.sdk.SDKUtil.java
/** * ?fileContent? base64DEFLATE?<br> * ??<br>/*from w w w.j a v a2s. c o m*/ * @param resData<br> * @param encoding ?encoding<br> */ public static void deCodeFileContent(Map<String, String> resData, String filePathRoot, String encoding) { // ? String fileContent = resData.get(SDKConstants.param_fileContent); if (null != fileContent && !"".equals(fileContent)) { try { byte[] fileArray = SecureUtil.inflater(SecureUtil.base64Decode(fileContent.getBytes(encoding))); String filePath = null; if (SDKUtil.isEmpty(resData.get("fileName"))) { filePath = filePathRoot + File.separator + resData.get("merId") + "_" + resData.get("batchNo") + "_" + resData.get("txnTime") + ".txt"; } else { filePath = filePathRoot + File.separator + resData.get("fileName"); } File file = new File(filePath); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream out = new FileOutputStream(file); out.write(fileArray, 0, fileArray.length); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:at.tugraz.sss.serv.SSFileU.java
public static void writeFileBytes(final FileOutputStream fileOut, final byte[] bytes, final Integer length) throws Exception { if (SSObjU.isNull(fileOut, bytes)) { throw new Exception("pars not okay"); }/*from www .j a v a 2 s. com*/ try { fileOut.write(bytes, 0, length); fileOut.flush(); } catch (Exception error) { throw error; } finally { if (fileOut != null) { fileOut.close(); } } }