List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:com.eurotong.orderhelperandroid.Common.java
@TargetApi(9) public static void downloadFile(String fileName) { try {//from w w w . java2 s. co m //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); Date date = new Date(); String datetime = dateFormat.format(date); // Create a URL for the desired page URL url = new URL( Common.GetBaseUrl() + Customer.Current().CustomerID + "/" + fileName + "?d=" + datetime); // Read all the text returned by the server BufferedInputStream in = new BufferedInputStream(url.openStream()); //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE); /* DataOutputStream out = new DataOutputStream(fos); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) Log.i(Define.APP_CATALOG, str); out.writeUTF(str); } */ BufferedOutputStream out = new BufferedOutputStream(fos, 4096); byte[] data = new byte[4096]; int bytesRead = 0, totalRead = 0; while ((bytesRead = in.read(data, 0, data.length)) >= 0) { out.write(data, 0, bytesRead); // update progress bar totalRead += bytesRead; /* int totalReadInKB = totalRead / 1024; msg = Message.obtain(parentActivity.activityHandler, AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0); parentActivity.activityHandler.sendMessage(msg); */ } in.close(); //fos.close(); out.close(); Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_file_finished), Toast.LENGTH_LONG).show(); try { if (fileName.equals(Define.MENU_FILE_NAME)) { Product.ParseMenuList(Common.GetFileInputStreamFromStorage(fileName)); Log.i(Define.APP_CATALOG, "menus size:" + ""); Product.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.BUSINESS_INFO_FILE_NAME)) { BusinessInfo bi = BusinessInfo .Parse(Common.GetFileInputStreamFromStorage(Define.BUSINESS_INFO_FILE_NAME)); Log.i(Define.APP_CATALOG, "setting: businessname:" + bi.getBusinessName()); BusinessInfo.Reload(); } else if (fileName.equals(Define.SETTING_FILE_NAME)) { Setting setting = Setting.Parse(Common.GetFileInputStreamFromStorage(Define.SETTING_FILE_NAME)); Log.i(Define.APP_CATALOG, "setting: printer port" + setting.getPrinterPort()); setting.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_BAR_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_BAR_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_BAR_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_KITCHEN_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_KITCHEN_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_KITCHEN_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.DEVICE_FILE)) { Device bi = Device.Parse(Common.GetFileInputStreamFromStorage(Define.DEVICE_FILE)); Log.i(Define.APP_CATALOG, Define.DEVICE_FILE); Device.Reload(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { Log.e(Define.APP_CATALOG, e.toString()); } catch (IOException e) { Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_error), Toast.LENGTH_LONG).show(); Log.e(Define.APP_CATALOG, e.toString()); e.printStackTrace(); } catch (Exception e) { Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_error), Toast.LENGTH_LONG).show(); Log.e(Define.APP_CATALOG, e.toString()); } }
From source file:com.wavemaker.tools.util.TomcatServer.java
public String deploy(File war, String contextRoot) { if (war == null) { throw new IllegalArgumentException("war cannot be null"); }/*from w w w. j a va 2 s .c om*/ if (!war.exists()) { throw new IllegalArgumentException("war does not exist"); } if (war.isDirectory()) { throw new IllegalArgumentException("war cannot be a directory"); } if (contextRoot == null) { contextRoot = StringUtils.fromFirstOccurrence(war.getName(), ".", -1); } contextRoot = checkContextRoot(contextRoot); if (isDeployed(contextRoot)) { undeploy(contextRoot); } String uri = getManagerUri() + "/deploy?" + getPathParam(contextRoot); HttpURLConnection con = super.getPutConnection(uri); con.setRequestProperty("Content-Type", "application/octet-stream"); con.setRequestProperty("Content-Length", String.valueOf(war.length())); prepareConnection(con); try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(war)); BufferedOutputStream bos = new BufferedOutputStream(con.getOutputStream()); IOUtils.copy(bis, bos); bis.close(); bos.close(); } catch (IOException ex) { throw new ConfigurationException(ex); } return ObjectUtils.toString(getResponse(con), ""); }
From source file:com.pipinan.githubcrawler.GithubCrawler.java
/** * * @param username the owner name of respoitory * @param reponame the name of respoitory * @param path which folder would you like to save the zip file * @throws IOException//w ww . ja v a 2 s .c o m */ public void crawlRepoZip(String username, String reponame, String path) throws IOException { GHRepository repo = github.getRepository(username + "/" + reponame); HttpClient httpclient = getHttpClient(); //the url pattern is https://github.com/"USER_NAME"/"REPO_NAME"/archive/master.zip HttpGet httpget = new HttpGet("https://github.com/" + username + "/" + reponame + "/archive/master.zip"); HttpResponse response = httpclient.execute(httpget); try { System.out.println(response.getStatusLine()); if (response.getStatusLine().toString().contains("200 OK")) { //the header "Content-Disposition: attachment; filename=JSON-java-master.zip" can find the filename String filename = null; Header[] headers = response.getHeaders("Content-Disposition"); for (Header header : headers) { System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); String tmp = header.getValue(); filename = tmp.substring(tmp.lastIndexOf("filename=") + 9); } if (filename == null) { System.err.println("Can not find the filename in the response."); System.exit(-1); } HttpEntity entity = response.getEntity(); BufferedInputStream bis = new BufferedInputStream(entity.getContent()); String filePath = path + filename; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); EntityUtils.consume(entity); } } finally { } }
From source file:com.yahoo.yrlhaifa.haifa_utils.utils.FileUtils.java
/** * @param src source/* w w w .j a va 2 s . c o m*/ * @param dst destination * @throws IOException io exception */ public static void copy(File src, File dst) throws IOException { BufferedInputStream reader = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(dst)); copy(reader, writer); writer.close(); reader.close(); }
From source file:org.kievguide.controller.PlaceController.java
@RequestMapping(value = "/addnewplace", method = RequestMethod.POST) public ModelAndView addNewPlace(HttpServletRequest request, @CookieValue(value = "userstatus", defaultValue = "guest") String useremail, @RequestParam("placename") String placename, @RequestParam("placedescription") String placedescription, @RequestParam("placeadress") String placeadress, @RequestParam("placemetro") Integer placemetro, @RequestParam("placephotosrc") MultipartFile file) throws IOException { ModelAndView modelAndView = new ModelAndView(); SecureRandom random = new SecureRandom(); String photoname = new BigInteger(130, random).toString(32); Place place = new Place(); User user = userService.searchUser(useremail); Station metroStation = stationService.findById(placemetro); System.out.println("========================================== metro = " + metroStation.getName()); place.setName(placename);// w w w.j a v a2s .c om place.setDescription(placedescription); place.setAdress(placeadress); place.setMetro(metroStation); place.setAuthorid(user); place.setPhotosrc("img/" + photoname + ".jpg"); place.setRatingcount(0); place.setRatingvalue(0.0); String folder = request.getSession().getServletContext().getRealPath(""); folder = folder.substring(0, 30); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg"))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); System.out.println( "========================================== ? ? = " + place.getName()); placeService.addPlace(place); return new ModelAndView("redirect:" + "firstrequest"); }
From source file:de.knurt.fam.template.controller.letter.EMailLetterAdapter.java
/** * send the email and return an errormessage. if errormessage is empty, * sending succeeded./*from w w w . j a v a2 s. com*/ * * @param post * getting the input stream from * @param customid * for the to send via email * @return an errormessage (may empty on success) */ public String send(PostMethod post, String customid) { String errormessage = ""; if (this.isValid()) { File file = null; try { file = this.getTmpFile(customid); } catch (IOException e) { FamLog.exception(e, 201106131728l); errormessage += "Fail: Create tmp file [201106131729]."; } try { InputStream is = post.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); int bite = 0; while ((bite = is.read()) >= 0) { bos.write(bite); } bos.flush(); bos.close(); } catch (IOException e) { errormessage += "Fail: Write pdf to tmp file [201106141055]."; FamLog.exception(e, 201106131733l); } Email mail = this.getEMail(file, this); if (mail == null) { errormessage += "Fail: Create e-mail object. Please check log files [201106141058]."; } boolean succ = UserMailSender.sendWithoutUserBox(mail); if (!succ) { errormessage += "Fail: Send email through configured server. Please check log files [201106131756]."; } } else { if (this.getTo() == null) { errormessage += "Fail: Find an recipient - form email_recipient sent? [201106131757]"; } else { errormessage += "Invalid email address. Recheck email recipient."; } } return errormessage; }
From source file:com.buaa.cfs.utils.FileUtil.java
private static void unpackEntries(TarArchiveInputStream tis, TarArchiveEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { File subDir = new File(outputDir, entry.getName()); if (!subDir.mkdirs() && !subDir.isDirectory()) { throw new IOException("Mkdirs failed to create tar internal dir " + outputDir); }//from w w w.j ava 2 s .co m for (TarArchiveEntry e : entry.getDirectoryEntries()) { unpackEntries(tis, e, subDir); } return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { throw new IOException("Mkdirs failed to create tar internal dir " + outputDir); } } int count; byte data[] = new byte[2048]; BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); while ((count = tis.read(data)) != -1) { outputStream.write(data, 0, count); } outputStream.flush(); outputStream.close(); }
From source file:com.parasoft.em.client.impl.JSONClient.java
protected JSONObject doPost(String restPath, JSONObject payload) throws IOException { HttpURLConnection connection = getConnection(restPath); connection.setRequestMethod("POST"); if (payload != null) { String payloadString = payload.toString(); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); BufferedOutputStream stream = new BufferedOutputStream(connection.getOutputStream()); try {/*from w w w .j av a2 s . c o m*/ byte[] bytes = payloadString.getBytes("UTF-8"); stream.write(bytes, 0, bytes.length); } finally { stream.close(); } } int responseCode = connection.getResponseCode(); if (responseCode / 100 == 2) { return getResponseJSON(connection.getInputStream()); } else { String errorMessage = getResponseString(connection.getErrorStream()); throw new IOException(restPath + ' ' + responseCode + '\n' + errorMessage); } }
From source file:logicProteinHypernetwork.analysis.complexes.offline.ComplexPredictionCommand.java
/** * Returns predicted complexes for a given undirected graph of proteins. * * @param g the graph/* ww w .j ava 2 s.co m*/ * @return the predicted complexes */ public Collection<Complex> transform(UndirectedGraph<Protein, Interaction> g) { try { Process p = Runtime.getRuntime().exec(command); BufferedOutputStream outputStream = new BufferedOutputStream(p.getOutputStream()); BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream()); for (Interaction i : g.getEdges()) { String out = i.first() + " pp " + i.second(); outputStream.write(out.getBytes()); } outputStream.close(); p.waitFor(); if (!hypernetwork.getProteins().hasIndex()) { hypernetwork.getProteins().buildIndex(); } Collection<Complex> complexes = new ArrayList<Complex>(); Scanner s = new Scanner(inputStream); Pattern rowPattern = Pattern.compile(".*?\\n"); Pattern proteinPattern = Pattern.compile(".*?\\s"); while (s.hasNext(rowPattern)) { Complex c = new Complex(); while (s.hasNext(proteinPattern)) { c.add(hypernetwork.getProteins().getProteinById(s.next(proteinPattern).trim())); } complexes.add(c); } inputStream.close(); return complexes; } catch (InterruptedException ex) { Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:org.iti.agrimarket.view.UserController.java
@RequestMapping(value = { "/uprofile.htm" }, method = RequestMethod.POST) public String updateUserProfile(@RequestParam(value = "fullName", required = true) String fullName, @RequestParam(value = "mobile", required = true) String mobil, @RequestParam(value = "governerate", required = true) String governerate, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Locale locale, Model model) { System.out.println("hhhhhhhhhhhhhhhhhhhhhh" + file.getName()); String language = locale.getLanguage(); locale = LocaleContextHolder.getLocale(); User user = (User) request.getSession().getAttribute("user"); if (user != null) { user.setFullName(fullName);/*from w w w. j a v a 2s. c o m*/ user.setGovernerate(governerate); if (file != null) { try { user.setImage(file.getBytes()); byte[] image = user.getImage(); MagicMatch match = null; try { match = Magic.getMagicMatch(image); } catch (MagicParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } catch (MagicMatchNotFoundException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } catch (MagicException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } String ext = null; if (match != null) ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( new File(Constants.IMAGE_PATH + Constants.USER_PATH + file.getOriginalFilename()))); stream.write(image); stream.close(); user.setImageUrl( Constants.IMAGE_PRE_URL + Constants.USER_PATH + file.getOriginalFilename() + ext); } catch (IOException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } user.setMobile(mobil); int res = userService.updateUser(user); if (res != 0) { request.getSession().setAttribute("user", user); } model.addAttribute("user", user); } model.addAttribute("lang", locale); return "profile"; }