List of usage examples for java.nio.channels Channels newOutputStream
public static OutputStream newOutputStream(AsynchronousByteChannel ch)
From source file:Main.java
public static void main(String[] argv) throws Exception { // Create a read/writeable file channel File file = new File("filename"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); OutputStream os = Channels.newOutputStream(channel); os.close();// ww w . j a v a2 s. co m }
From source file:Test.java
private static void clientStart() { try {//from w w w.jav a 2 s. co m InetSocketAddress hostAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 2583); AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open(); Future<Void> connectFuture = clientSocketChannel.connect(hostAddress); connectFuture.get(); // Wait until connection is done. OutputStream os = Channels.newOutputStream(clientSocketChannel); ObjectOutputStream oos = new ObjectOutputStream(os); for (int i = 0; i < 5; i++) { oos.writeObject("Look at me " + i); Thread.sleep(1000); } oos.writeObject("EOF"); oos.close(); clientSocketChannel.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.arcbees.bourseje.server.upload.CloudStorageUploadService.java
@Override public String upload(String name, InputStream inputStream, long size) { GcsOutputChannel outputChannel;//w ww .j a v a2s . c om GcsFileOptions options = GcsFileOptions.getDefaultInstance(); GcsFilename fileName = getFileName(name); verifyFileExtension(name); try { outputChannel = gcsService.createOrReplace(fileName, options); // IOUtils cause an INVALID_BLOB_KEY Exception copy(inputStream, Channels.newOutputStream(outputChannel)); } catch (IOException e) { throw new RuntimeException(e); } return getServingUrl(fileName); }
From source file:edu.teco.smartlambda.container.docker.HttpHijackingWorkaround.java
/** * Get a output stream that can be used to write into the standard input stream of docker container's running process * * @param stream the docker container's log stream * @param uri the URI to the docker socket * * @return a writable byte channel that can be used to write into the http web-socket output stream * * @throws Exception on any docker or reflection exception *//* w w w .java 2 s . co m*/ static OutputStream getOutputStream(final LogStream stream, final String uri) throws Exception { // @formatter:off final String[] fields = new String[] { "reader", "stream", "original", "input", "in", "in", "in", "eofWatcher", "wrappedEntity", "content", "in", "instream" }; final String[] containingClasses = new String[] { "com.spotify.docker.client.DefaultLogStream", LogReader.class.getName(), "org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream", EntityInputStream.class.getName(), FilterInputStream.class.getName(), FilterInputStream.class.getName(), FilterInputStream.class.getName(), EofSensorInputStream.class.getName(), HttpEntityWrapper.class.getName(), BasicHttpEntity.class.getName(), IdentityInputStream.class.getName(), SessionInputBufferImpl.class.getName() }; // @formatter:on final List<String[]> fieldClassTuples = new LinkedList<>(); for (int i = 0; i < fields.length; i++) { fieldClassTuples.add(new String[] { containingClasses[i], fields[i] }); } if (uri.startsWith("unix:")) { fieldClassTuples.add(new String[] { ChannelInputStream.class.getName(), "ch" }); } else if (uri.startsWith("https:")) { final float jvmVersion = Float.parseFloat(System.getProperty("java.specification.version")); fieldClassTuples .add(new String[] { "sun.security.ssl.AppInputStream", jvmVersion < 1.9f ? "c" : "socket" }); } else { fieldClassTuples.add(new String[] { "java.net.SocketInputStream", "socket" }); } final Object res = getInternalField(stream, fieldClassTuples); if (res instanceof WritableByteChannel) { return Channels.newOutputStream((WritableByteChannel) res); } else if (res instanceof Socket) { return ((Socket) res).getOutputStream(); } else { throw new AssertionError("Expected " + WritableByteChannel.class.getName() + " or " + Socket.class.getName() + " but found: " + res.getClass().getName()); } }
From source file:io.druid.query.groupby.epinephelinae.LimitedTemporaryStorage.java
/** * Create a new temporary file. All methods of the returned output stream may throw * {@link TemporaryStorageFullException} if the temporary storage area fills up. * * @return output stream to the file//from w ww. ja va 2 s .c om * * @throws TemporaryStorageFullException if the temporary storage area is full * @throws IOException if something goes wrong while creating the file */ public LimitedOutputStream createFile() throws IOException { if (bytesUsed.get() >= maxBytesUsed) { throw new TemporaryStorageFullException(maxBytesUsed); } synchronized (files) { if (closed) { throw new ISE("Closed"); } FileUtils.forceMkdir(storageDirectory); final File theFile = new File(storageDirectory, StringUtils.format("%08d.tmp", files.size())); final EnumSet<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); final FileChannel channel = FileChannel.open(theFile.toPath(), openOptions); files.add(theFile); return new LimitedOutputStream(theFile, Channels.newOutputStream(channel)); } }
From source file:com.chicm.cmraft.rpc.PacketUtils.java
private static int writeRpc_backup(SocketChannel channel, Message header, Message body, int totalSize) throws IOException { // writing total size so that server can read all request data in one read LOG.debug("total size:" + totalSize); long t = System.currentTimeMillis(); OutputStream os = Channels.newOutputStream(channel); writeIntToStream(totalSize, os);//from ww w . jav a2 s.c o m header.writeDelimitedTo(os); if (body != null) body.writeDelimitedTo(os); os.flush(); LOG.debug("" + (System.currentTimeMillis() - t) + " ms"); LOG.debug("flushed:" + totalSize); return totalSize; }
From source file:com.newatlanta.appengine.vfs.provider.GaeRandomAccessContent.java
GaeRandomAccessContent(GaeFileObject gfo, RandomAccessMode m, boolean append) throws IOException { EnumSet<StandardOpenOption> options = EnumSet.of(StandardOpenOption.READ); if (m == RandomAccessMode.READWRITE) { options.add(StandardOpenOption.WRITE); gfo.doSetLastModTime(System.currentTimeMillis()); }//from ww w. java 2 s.co m if (append) { options.add(StandardOpenOption.APPEND); } fileChannel = new GaeFileChannel(gfo, options); dataOutput = new DataOutputStream(Channels.newOutputStream(fileChannel)); dataInput = new GaeDataInputStream(Channels.newInputStream(fileChannel)); }
From source file:org.darkware.wpman.wpcli.WPCLI.java
/** * Update the local WP-CLI tool to the most recent version. */// w w w.j a va 2 s . c o m public static void update() { try { WPManager.log.info("Downloading new version of WP-CLI."); CloseableHttpClient httpclient = HttpClients.createDefault(); URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com") .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build(); WPManager.log.info("Downloading from: {}", pharURI); HttpGet downloadRequest = new HttpGet(pharURI); CloseableHttpResponse response = httpclient.execute(downloadRequest); WPManager.log.info("Download response: {}", response.getStatusLine()); WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue()); FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); response.getEntity().writeTo(Channels.newOutputStream(wpcliFile)); wpcliFile.close(); Set<PosixFilePermission> wpcliPerms = new HashSet<>(); wpcliPerms.add(PosixFilePermission.OWNER_READ); wpcliPerms.add(PosixFilePermission.OWNER_WRITE); wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE); wpcliPerms.add(PosixFilePermission.GROUP_READ); wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms); } catch (URISyntaxException e) { WPManager.log.error("Failure building URL for WPCLI download.", e); System.exit(1); } catch (IOException e) { WPManager.log.error("Error while downloading WPCLI client.", e); e.printStackTrace(); System.exit(1); } }
From source file:com.thinkberg.moxo.vfs.s3.jets3t.Jets3tFileObject.java
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception { changed = true;// w w w . j a va 2s .co m return Channels.newOutputStream(getCacheFileChannel()); }
From source file:com.gamesalutes.utils.ByteUtils.java
/** * Returns a <code>ByteBuffer</code> containing the byte representation * of the serializable object <code>obj</code>. * // w w w. jav a2 s .co m * @param obj the <code>Object</code> to convert to its byte representation * @param buf an existing buffer to use for storage or <code>null</code> to create new buffer. * If <code>buf</code> is not large enough it will be expanded using {@link #growBuffer(ByteBuffer, int)} * @return <code>ByteBuffer</code> containing the byte representation * of <code>obj</code>. * * @throws IOException if <code>obj</code> is not serializable or error occurs while writing the bytes */ public static ByteBuffer getObjectBytes(Object obj, ByteBuffer buf) throws IOException { if (buf == null) buf = ByteBuffer.allocate(READ_BUFFER_SIZE); // note the input position int startPos = buf.position(); ByteBufferChannel channel = new ByteBufferChannel(buf); ObjectOutputStream out = null; try { out = new ObjectOutputStream(Channels.newOutputStream(channel)); out.writeObject(obj); out.flush(); } finally { MiscUtils.closeStream(out); } ByteBuffer returnBuf = channel.getByteBuffer(); returnBuf.flip(); // reset starting position to be that of input buffer returnBuf.position(startPos); return returnBuf; }