List of usage examples for java.nio.channels ReadableByteChannel close
public void close() throws IOException;
From source file:eu.ensure.aging.AgingSimulator.java
public static void main(String[] args) { Options options = new Options(); options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file"); options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file"); options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)"); Properties properties = new Properties(); CommandLineParser parser = new PosixParser(); try {/*from ww w .j av a 2 s . com*/ CommandLine line = parser.parse(options, args); // if (line.hasOption("flip-bit-in-name")) { properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name")); } else { // On by default (if not explicitly de-activated above) properties.put("flip-bit-in-name", "true"); } // if (line.hasOption("flip-bit-in-uname")) { properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname")); } else { properties.put("flip-bit-in-uname", "false"); } // if (line.hasOption("update-checksum")) { properties.put("update-checksum", line.getOptionValue("update-checksum")); } else { properties.put("update-checksum", "false"); } String[] fileArgs = line.getArgs(); if (fileArgs.length < 1) { printHelp(options, System.err); System.exit(1); } String srcPath = fileArgs[0]; File srcAIP = new File(srcPath); if (!srcAIP.exists()) { String info = "The source path does not locate a file: " + srcPath; System.err.println(info); System.exit(1); } if (srcAIP.isDirectory()) { String info = "The source path locates a directory, not a file: " + srcPath; System.err.println(info); System.exit(1); } if (!srcAIP.canRead()) { String info = "Cannot read source file: " + srcPath; System.err.println(info); System.exit(1); } boolean doReplace = false; File destAIP = null; if (fileArgs.length > 1) { String destPath = fileArgs[1]; destAIP = new File(destPath); if (destAIP.exists()) { String info = "The destination path locates an existing file: " + destPath; System.err.println(info); System.exit(1); } } else { doReplace = true; try { destAIP = File.createTempFile("tmp-aged-aip-", ".tar"); } catch (IOException ioe) { String info = "Failed to create temporary file: "; info += ioe.getMessage(); System.err.println(info); System.exit(1); } } String info = "Age simulation\n"; info += " Reading from " + srcAIP.getName() + "\n"; if (doReplace) { info += " and replacing it's content"; } else { info += " Writing to " + destAIP.getName(); } System.out.println(info); // InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(srcAIP)); os = new BufferedOutputStream(new FileOutputStream(destAIP)); simulateAging(srcAIP.getName(), is, os, properties); } catch (FileNotFoundException fnfe) { info = "Could not locate file: " + fnfe.getMessage(); System.err.println(info); } finally { try { if (null != os) os.close(); if (null != is) is.close(); } catch (IOException ignore) { } } // if (doReplace) { File renamedOriginal = new File(srcAIP.getName() + "-backup"); srcAIP.renameTo(renamedOriginal); ReadableByteChannel rbc = null; WritableByteChannel wbc = null; try { rbc = Channels.newChannel(new FileInputStream(destAIP)); wbc = Channels.newChannel(new FileOutputStream(srcAIP)); FileIO.fastChannelCopy(rbc, wbc); } catch (FileNotFoundException fnfe) { info = "Could not locate temporary output file: " + fnfe.getMessage(); System.err.println(info); } catch (IOException ioe) { info = "Could not copy temporary output file over original AIP: " + ioe.getMessage(); System.err.println(info); } finally { try { if (null != wbc) wbc.close(); if (null != rbc) rbc.close(); destAIP.delete(); } catch (IOException ignore) { } } } } catch (ParseException pe) { String info = "Failed to parse command line: " + pe.getMessage(); System.err.println(info); printHelp(options, System.err); System.exit(1); } }
From source file:org.ops4j.pax.runner.platform.internal.StreamUtils.java
/** * Copy a stream to a destination. It does not close the streams. * * @param in the stream to copy from * @param out the stream to copy to * @param progressBar download progress feedback. Can be null. * * @throws IOException re-thrown/* www .j a va 2s . c o m*/ */ public static void streamCopy(final InputStream in, final FileChannel out, final ProgressBar progressBar) throws IOException { NullArgumentException.validateNotNull(in, "Input stream"); NullArgumentException.validateNotNull(out, "Output stream"); final long start = System.currentTimeMillis(); long bytes = 0; ProgressBar feedbackBar = progressBar; if (feedbackBar == null) { feedbackBar = new NullProgressBar(); } try { ReadableByteChannel inChannel = Channels.newChannel(in); bytes = out.transferFrom(inChannel, 0, Integer.MAX_VALUE); inChannel.close(); } finally { feedbackBar.increment(bytes, bytes / Math.max(System.currentTimeMillis() - start, 1)); feedbackBar.stop(); } }
From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java
/** * Return the {@link HttpTunnelPayload} for the given message or {@code null} if there * is no payload.// ww w . j a va 2 s .c o m * @param message the HTTP message * @return the payload or {@code null} * @throws IOException in case of I/O errors */ public static HttpTunnelPayload get(HttpInputMessage message) throws IOException { long length = message.getHeaders().getContentLength(); if (length <= 0) { return null; } String seqHeader = message.getHeaders().getFirst(SEQ_HEADER); Assert.state(StringUtils.hasLength(seqHeader), "Missing sequence header"); ReadableByteChannel body = Channels.newChannel(message.getBody()); ByteBuffer payload = ByteBuffer.allocate((int) length); while (payload.hasRemaining()) { body.read(payload); } body.close(); payload.flip(); return new HttpTunnelPayload(Long.valueOf(seqHeader), payload); }
From source file:IOUtilities.java
/** * Copy ALL available data from one stream into another * @param in//from w w w . j av a 2s . co m * @param out * @throws IOException */ public static void copy(InputStream in, OutputStream out) throws IOException { ReadableByteChannel source = Channels.newChannel(in); WritableByteChannel target = Channels.newChannel(out); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (source.read(buffer) != -1) { buffer.flip(); // Prepare the buffer to be drained while (buffer.hasRemaining()) { target.write(buffer); } buffer.clear(); // Empty buffer to get ready for filling } source.close(); target.close(); }
From source file:org.geowebcache.util.ResponseUtils.java
private static void loadBlankTile(Resource blankTile, URL source) throws IOException { InputStream inputStream = source.openStream(); ReadableByteChannel ch = Channels.newChannel(inputStream); try {//from w ww . j a v a2 s . c o m blankTile.transferFrom(ch); } catch (IOException e) { e.printStackTrace(); } finally { ch.close(); } }
From source file:com.thinkberg.webdav.Util.java
public static long copyStream(final InputStream is, final OutputStream os) throws IOException { ReadableByteChannel rbc = Channels.newChannel(is); WritableByteChannel wbc = Channels.newChannel(os); int bytesWritten = 0; final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (rbc.read(buffer) != -1) { buffer.flip();/*w w w.j a va2 s .c om*/ bytesWritten += wbc.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { bytesWritten += wbc.write(buffer); } rbc.close(); wbc.close(); return bytesWritten; }
From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java
/** * ??// w w w . j a v a 2 s . c o m * * @param is * @return * @throws IOException */ public static String readStreamAsStr(InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); WritableByteChannel dest = Channels.newChannel(bos); ReadableByteChannel src = Channels.newChannel(is); ByteBuffer bb = ByteBuffer.allocate(4096); while (src.read(bb) != -1) { bb.flip(); dest.write(bb); bb.clear(); } src.close(); dest.close(); return new String(bos.toByteArray(), Constants.ENCODING); }
From source file:StreamUtil.java
/** * Copies the content read from InputStream to OutputStream. Uses the NIO Channels to copy. * @param is The InputStream that is read. * @param os The OutputStream where the data is written. * @throws IOException/* w w w . j a v a 2 s .com*/ */ public static void copy(final InputStream is, final OutputStream os) throws IOException { final ReadableByteChannel inChannel = Channels.newChannel(is); final WritableByteChannel outChannel = Channels.newChannel(os); try { final ByteBuffer buffer = ByteBuffer.allocate(65536); while (true) { int bytesRead = inChannel.read(buffer); if (bytesRead == -1) break; buffer.flip(); while (buffer.hasRemaining()) outChannel.write(buffer); buffer.clear(); } } finally { try { inChannel.close(); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } try { outChannel.close(); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } }
From source file:com.pavlospt.rxfile.RxFile.java
private static File fileFromUri(Context context, Uri data) throws Exception { DocumentFile file = DocumentFile.fromSingleUri(context, data); String fileType = file.getType(); String fileName = file.getName(); File fileCreated;// w ww .j a va2s. c om ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor()); logDebug("External cache dir:" + context.getExternalCacheDir()); String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName; String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1); String mimeType = getMimeType(fileName); logDebug("From Google Drive guessed type: " + getMimeType(fileName)); logDebug("Extension: " + fileExtension); if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) { filePath += "." + Constants.PDF_EXTENSION; } if (!createFile(filePath)) { return new File(filePath); } ReadableByteChannel from = Channels.newChannel(inputStream); WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath)); fastChannelCopy(from, to); from.close(); to.close(); fileCreated = new File(filePath); logDebug("Path for made file: " + fileCreated.getAbsolutePath()); return fileCreated; }
From source file:com.xxxifan.devbox.library.rxfile.RxFile.java
private static File fileFromUri(Context context, Uri data) throws Exception { DocumentFile file = DocumentFile.fromSingleUri(context, data); String fileType = file.getType(); String fileName = file.getName(); File fileCreated;// w ww.j a v a 2 s .c o m ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor()); Log.e(TAG, "External cache dir:" + context.getExternalCacheDir()); String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName; String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1); String mimeType = getMimeType(fileName); Log.e(TAG, "From Drive guessed type: " + getMimeType(fileName)); Log.e(TAG, "Extension: " + fileExtension); if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) { filePath += "." + Constants.PDF_EXTENSION; } if (!createFile(filePath)) { return new File(filePath); } ReadableByteChannel from = Channels.newChannel(inputStream); WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath)); fastChannelCopy(from, to); from.close(); to.close(); fileCreated = new File(filePath); Log.e(TAG, "Path for made file: " + fileCreated.getAbsolutePath()); return fileCreated; }