List of usage examples for java.io OutputStream close
public void close() throws IOException
From source file:Base64.java
private static void writeBytes(final File file, final byte[] data) { try {// ww w . j a v a 2s . co m final OutputStream fos = new FileOutputStream(file); final OutputStream os = new BufferedOutputStream(fos); os.write(data); os.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:bluevia.SendSMS.java
public static void setFacebookWallPost(String userEmail, String post) { try {/*from w w w. j a va2 s . c o m*/ Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID); if (facebookAccount != null) { String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); Entity blueviaUser = Util.getUser(userEmail); //FIXME URL fbAPI = new URL( "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed"); HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection(); String content = String.format("access_token=%s&message=%s", access_key, URLEncoder.encode(post, "UTF-8")); request.setRequestMethod("POST"); request.setRequestProperty("Content-Type", "javascript/text"); request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length)); request.setDoOutput(true); request.setDoInput(true); OutputStream os = request.getOutputStream(); os.write(content.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { StringBuffer body = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) body.append(line); } while (line != null); JSONObject id = new JSONObject(body.toString()); } else log.severe( String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage())); } } catch (Exception e) { log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage())); } }
From source file:backup.BackupMaker.java
private static void tryToCloseOutputStreams(OutputStream... streams) { for (OutputStream st : streams) try {// w w w . j a v a2 s. c o m st.close(); } catch (IOException e) { System.err.println(e); ExitCodes.exit(ExitCodes.EX_IOERR, " Error trying to close the output file stream."); } }
From source file:Main.java
public static File getFile(Context context, Uri uri, boolean forceCreation) { if (!forceCreation && "file".equalsIgnoreCase(uri.getScheme())) { return new File(uri.getPath()); }/*from w w w. ja v a 2s. com*/ File file = null; try { File root = context.getFilesDir(); if (root == null) { throw new Exception("data dir not found"); } file = new File(root, getFilename(context, uri)); file.delete(); InputStream is = context.getContentResolver().openInputStream(uri); OutputStream os = new FileOutputStream(file); byte[] buf = new byte[1024]; int cnt = is.read(buf); while (cnt > 0) { os.write(buf, 0, cnt); cnt = is.read(buf); } os.close(); is.close(); file.deleteOnExit(); } catch (Exception e) { Log.e("OpenFile", e.getMessage(), e); } return file; }
From source file:Main.java
public static String UpdateScore(String userName, int br) { String retStr = ""; try {//w ww . ja va 2 s . c om URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("broj", br); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:io.undertow.server.handlers.ChunkedRequestTransferCodingTestCase.java
@BeforeClass public static void setup() { final BlockingHandler blockingHandler = new BlockingHandler(); DefaultServer.setRootHandler(blockingHandler); blockingHandler.setRootHandler(new HttpHandler() { @Override//from ww w . j a va2 s . c om public void handleRequest(final HttpServerExchange exchange) { try { if (connection == null) { connection = exchange.getConnection(); } else if (!DefaultServer.isAjp() && !DefaultServer.isProxy() && connection != exchange.getConnection()) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); final OutputStream outputStream = exchange.getOutputStream(); outputStream.write("Connection not persistent".getBytes()); outputStream.close(); return; } final OutputStream outputStream = exchange.getOutputStream(); final InputStream inputStream = exchange.getInputStream(); String m = HttpClientUtils.readResponse(inputStream); Assert.assertEquals(message.length(), m.length()); Assert.assertEquals(message, m); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } }); }
From source file:com.cloudbees.workflow.Util.java
public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType) throws IOException { String jenkinsUrl = jenkins.getRootUrl(); URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/")); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); try {/*from w w w . java 2 s .c o m*/ conn.setRequestMethod("POST"); // Set the crumb header, otherwise the POST may be rejected. NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins); conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue()); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } if (content != null) { byte[] bytes = content.getBytes(Charset.forName("UTF-8")); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); final OutputStream os = conn.getOutputStream(); try { os.write(bytes); os.flush(); } finally { os.close(); } } return conn.getResponseCode(); } finally { conn.disconnect(); } }
From source file:edu.isi.webserver.FileUtil.java
public static void copyFiles(File destination, File source) throws FileNotFoundException, IOException { if (!destination.exists()) destination.createNewFile();/* w w w. java2 s. c o m*/ InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); logger.debug("Done copying contents of " + source.getName() + " to " + destination.getName()); }
From source file:Main.java
public static long getFirstInstalled() { long firstInstalled = 0; PackageManager pm = myApp.getPackageManager(); try {/* w w w . ja v a 2 s. co m*/ PackageInfo pi = pm.getPackageInfo(myApp.getApplicationContext().getPackageName(), pm.GET_SIGNATURES); try { try { //noinspection AndroidLintNewApi firstInstalled = pi.firstInstallTime; } catch (NoSuchFieldError e) { } } catch (Exception ee) { } if (firstInstalled == 0) { // old versions of Android don't have firstInstallTime in PackageInfo File dir; try { dir = new File( getApp().getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/.config"); } catch (Exception e) { dir = null; } if (dir != null && (dir.exists() || dir.mkdirs())) { File fTimeStamp = new File(dir.getAbsolutePath() + "/.myconfig"); if (fTimeStamp.exists()) { firstInstalled = fTimeStamp.lastModified(); } else { // create this file - to make it slightly more confusing, write the signature there OutputStream out; try { out = new FileOutputStream(fTimeStamp); out.write(pi.signatures[0].toByteArray()); out.flush(); out.close(); } catch (Exception e) { } } } } } catch (PackageManager.NameNotFoundException e) { } return firstInstalled; }
From source file:com.floreantpos.license.FiveStarPOSLicenseGenerator.java
public static String generateLicense(Properties templateProperties, InputStream privateKeyInputStream, File licenseFile) throws FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException, SignatureException { PrivateKey privateKey = readPrivateKey(privateKeyInputStream); String encoded = templateProperties.toString(); String signature = FiveStarPOSLicenseGenerator.sign(encoded.getBytes(), privateKey); OutputStream output = new FileOutputStream(licenseFile); Properties licenseProperties = new OrderedProperties(); licenseProperties.putAll(templateProperties); licenseProperties.setProperty(License.SIGNATURE, signature); licenseProperties.store(output, "License file"); output.close(); return signature; }