canonical example by Tabnine
public void postRequest(String urlStr, String jsonBodyStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/json"); try (OutputStream outputStream = httpURLConnection.getOutputStream()) { outputStream.write(jsonBodyStr.getBytes()); outputStream.flush(); } if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { // ... do something with line } } } else { // ... do something with unsuccessful response } }
/** * Copy the contents of the given InputStream to the given OutputStream. * Leaves both streams open when done. * @param in the InputStream to copy from * @param out the OutputStream to copy to * @return the number of bytes copied * @throws IOException in case of I/O errors */ public static int copy(InputStream in, OutputStream out) throws IOException { Assert.notNull(in, "No InputStream specified"); Assert.notNull(out, "No OutputStream specified"); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); return byteCount; }
//create a file to write bitmap data File f = new File(context.getCacheDir(), filename); f.createNewFile(); //Convert bitmap to byte array Bitmap bitmap = your bitmap; ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); fos.flush(); fos.close();
// Assume block needs to be inside a Try/Catch block. String path = Environment.getExternalStorageDirectory().toString(); OutputStream fOut = null; Integer counter = 0; File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten. fOut = new FileOutputStream(file); Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate fOut.flush(); // Not really required fOut.close(); // do not forget to close the stream MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
InputStream is = new BufferedInputStream(sess.getStdout(), 40000); os.write(0x0); os.flush(); int c = is.read(); if (c < 0) throw new IOException("Remote scp terminated unexpectedly."); os.write(0x0); os.flush(); File f = new File(target + File.separatorChar + lnp.filename); FileOutputStream fop = null; fop = new FileOutputStream(f); trans = (int) remain; int this_time_received = is.read(buffer, 0, trans); fop.close(); } catch (IOException e) { if (fop != null) fop.close(); os.write(0x0); os.flush();
/** * Flushes any pending data and closes output file. If writing to an * OutputStream, the stream is not closed. */ public boolean finish() { if (!started) return false; boolean ok = true; started = false; try { out.write(0x3b); // GIF trailer out.flush(); if (closeStream) { out.close(); } } catch (IOException e) { ok = false; } // reset for subsequent use transIndex = 0; out = null; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; return ok; }
private void save() { try (OutputStream os = new FileOutputStream(new File(_historyFilePath)); ObjectOutputStream obos = new ObjectOutputStream(os)) { obos.writeObject(this); obos.flush(); os.flush(); } catch (IOException e) { LOGGER.warn("Could not update stats file {}", _historyFile, e); } }
FileOutputStream fos = new FileOutputStream("c:/myconfig.property"); Properties prop = new Properties(); prop.put("com.app.port", "8080"); prop.put("com.app.ip", "127.0.0.1"); prop.store(fos, "A Test to write properties"); fos.flush(); Properties prop2 = new Properties(); prop2.put("com.app.another", "Hello World"); prop2.store(fos, "Where does this go?"); fos.flush(); fos.close();
File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer!
protected final String sendPostRequest(String request) throws IOException { URL url = new URL("http", DEFAULT_HOST, this.port, request); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write("".getBytes()); out.flush(); InputStream in = con.getInputStream(); String response = CharStreams.toString(new InputStreamReader(con.getInputStream())); in.close(); return response; }
public static boolean write(Bitmap image, String type, File file) throws IOException { OutputStream stream = null; try { stream = new FileOutputStream(file); return write(image, type, stream); } catch (IOException ioe) { throw ioe; } finally { if (stream != null) { stream.flush(); stream.close(); } } } }
final void process(Socket clnt) throws IOException { InputStream in = new BufferedInputStream(clnt.getInputStream()); String cmd = readLine(in); logging(clnt.getInetAddress().getHostName(), new Date().toString(), cmd); while (skipLine(in) > 0){ } OutputStream out = new BufferedOutputStream(clnt.getOutputStream()); try { doReply(in, out, cmd); } catch (BadHttpRequest e) { replyError(out, e); } out.flush(); in.close(); out.close(); clnt.close(); }
FileOutputStream out = new FileOutputStream(filename); [...] out.flush(); out.getFD().sync();
OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk"); while ((count = input.read(data)) != -1) { total += count; resultData.putInt("progress" ,(int) (total * 100 / fileLength)); receiver.send(UPDATE_PROGRESS, resultData); output.write(data, 0, count); output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace();
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PhysicsSketchpad"; File dir = new File(file_path); if(!dir.exists()) dir.mkdirs(); File file = new File(dir, "sketchpad" + pad.t_id + ".png"); FileOutputStream fOut = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut); fOut.flush(); fOut.close();
public static void writeStringToFile(File file, String data, String encoding) throws IOException { OutputStream os = null; try { os = new FileOutputStream(file); os.write(data.getBytes(encoding)); os.flush(); } finally { if (null != os) { os.close(); } } }
/** * Copies information from the input stream to the output stream using * the specified buffer size * @throws java.io.IOException */ public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException { byte[] buf = new byte[bufferSize]; int bytesRead = input.read(buf); while (bytesRead != -1) { output.write(buf, 0, bytesRead); bytesRead = input.read(buf); } output.flush(); }