java.nio.channels.Channels Java Examples
The following examples show how to use
java.nio.channels.Channels.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelsTest.java From j2objc with Apache License 2.0 | 7 votes |
public void testNewInputStreamReadableByteChannel() throws Exception { ByteBuffer readbcbuf = ByteBuffer.allocateDirect(this.testNum); byte[] readbuf = new byte[this.testNum]; this.fins = new FileInputStream(tmpFile); ReadableByteChannel readbc = this.fins.getChannel(); assertEquals(this.fileSize, this.fins.available()); assertTrue(readbc.isOpen()); InputStream testins = Channels.newInputStream(readbc); // read in testins and fins use the same pointer testins.read(readbuf); assertEquals(this.fins.available(), this.fileSize - this.testNum); int readNum = readbc.read(readbcbuf); assertEquals(readNum, this.testNum); assertEquals(this.fins.available(), this.fileSize - this.testNum * 2); testins.read(readbuf); assertEquals(this.fins.available(), this.fileSize - this.testNum * 3); // readbc.close() affect testins readbc.close(); assertFalse(readbc.isOpen()); try { testins.read(readbuf); fail(); } catch (ClosedChannelException e) { // correct } }
Example #2
Source File: ConnectionCostsCompiler.java From deeplearning4j with Apache License 2.0 | 6 votes |
@Override public void compile() throws IOException { DataOutputStream dataOutput = new DataOutputStream(new BufferedOutputStream(output)); dataOutput.writeInt(cardinality); dataOutput.writeInt(bufferSize * SHORT_BYTES); ByteBuffer byteBuffer = ByteBuffer.allocate(costs.array().length * SHORT_BYTES); for (short cost : this.costs.array()) { byteBuffer.putShort(cost); } WritableByteChannel channel = Channels.newChannel(dataOutput); byteBuffer.flip(); channel.write(byteBuffer); dataOutput.close(); }
Example #3
Source File: S3SeekableByteChannel.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
private void openChannel(long position) throws IOException { try { S3Object object = S3Utils.getObject(uri, connection.getService(), position); is = S3Utils.getObjectInputStream(object); channel = Channels.newChannel(is); // use getInstanceLength(), not getContentLength()! this.size = object.getObjectMetadata().getInstanceLength(); } catch (IOException ioe) { try { closeChannel(); } catch (Exception e2) { ioe.addSuppressed(e2); } throw ioe; } }
Example #4
Source File: SQLScriptParserTest.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
private static List<String> parse(int expectedCount, String str, String delimiter, boolean backslashQuoteEscaping) throws IOException { Charset charset = Charset.defaultCharset(); SQLScriptParser sqlScriptParser = new SQLScriptParser(); sqlScriptParser.setBackslashQuoteEscaping(backslashQuoteEscaping); sqlScriptParser.setDelimiter(delimiter); sqlScriptParser.setStringInput(str); parse(expectedCount, sqlScriptParser); ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes(charset)); sqlScriptParser.setStreamInput(stream, charset); parse(expectedCount, sqlScriptParser); ByteArrayInputStream streamForChannel = new ByteArrayInputStream(str.getBytes(charset)); ReadableByteChannel channel = Channels.newChannel(streamForChannel); sqlScriptParser.setChannelInput(channel, charset); return parse(expectedCount, sqlScriptParser); }
Example #5
Source File: FileUtil.java From FairEmail with GNU General Public License v3.0 | 6 votes |
/** * Copies data from the input channel to the output file channel. * * @param input the input channel to copy. * @param output the output channel to copy. * @throws IOException if there is an I/O error. */ @SuppressLint("LambdaLast") public static void copy(@NonNull ReadableByteChannel input, @NonNull FileChannel output) throws IOException { try { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { output.transferFrom(input, 0, Long.MAX_VALUE); } else { InputStream inputStream = Channels.newInputStream(input); OutputStream outputStream = Channels.newOutputStream(output); int length; byte[] buffer = new byte[1024 * 4]; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } output.force(false); } finally { input.close(); output.close(); } }
Example #6
Source File: MyClassLoader.java From java-tutorial with MIT License | 6 votes |
/** * 读入.class的字节,因此要使用字节流 * * 一个Buffer对象是固定数量的数据的容器。其作用是一个存储器,或者分段运输区,在这里数据可被存储并在之后用于检索。 * * 尽管缓冲区作用于它们存储的原始数据类型,但缓冲区十分倾向于处理字节。 * NIO里,一个通道(channel)可以表示任何可以读写的对象。它的作用是为文件和套接口提供抽象 * * @param file * @return * @throws IOException */ private byte[] getClassBytes(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); //通道(Channel)是一种途径,借助该途径,可以用最小的总开销来访问操作系统本身的 I/O 服务。 //缓冲区(Buffer)则是通道内部用来发送和接收数据的端点。通道channel充当连接I/O服务的导管 FileChannel channel = inputStream.getChannel(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // WritableByteChannel 接口以提供 master( )方法 WritableByteChannel byteChannel = Channels.newChannel(outputStream); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int i = channel.read(buffer); if (i == 0 || i == -1) { break; } buffer.flip(); //写模式转换成读模式 byteChannel.write(buffer); buffer.clear(); } inputStream.close(); return outputStream.toByteArray(); }
Example #7
Source File: EmbeddedGithubJsonToParquet.java From incubator-gobblin with Apache License 2.0 | 6 votes |
private void downloadFile(String fileUrl, Path destination) { if (destination.toFile().exists()) { Log.info(String.format("Skipping download for %s at %s because destination already exists", fileUrl, destination.toString())); return; } try { URL archiveUrl = new URL(fileUrl); ReadableByteChannel rbc = Channels.newChannel(archiveUrl.openStream()); FileOutputStream fos = new FileOutputStream(String.valueOf(destination)); Log.info(String.format("Downloading %s at %s", fileUrl, destination.toString())); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); Log.info(String.format("Download complete for %s at %s", fileUrl, destination.toString())); } catch (IOException e) { e.printStackTrace(); } }
Example #8
Source File: BaseLoader.java From nd4j with Apache License 2.0 | 6 votes |
/** * Load an ndarray from a blob * * @param blob the blob to load from * @return the loaded ndarray */ @Override public INDArray load(Blob blob) throws SQLException { if (blob == null) return null; try(InputStream is = blob.getBinaryStream()) { ByteBuffer direct = ByteBuffer.allocateDirect((int) blob.length()); ReadableByteChannel readableByteChannel = Channels.newChannel(is); readableByteChannel.read(direct); Buffer byteBuffer = (Buffer) direct; byteBuffer.rewind(); return BinarySerde.toArray(direct); } catch (Exception e) { throw new RuntimeException(e); } }
Example #9
Source File: ClassClassLoader.java From onlineJavaIde with MIT License | 6 votes |
private byte[] getClassFileBytes(String classFile) throws Exception { //采用NIO读取 FileInputStream fis = new FileInputStream(classFile); FileChannel fileC = fis.getChannel(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel outC = Channels.newChannel(baos); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); while (true) { int i = fileC.read(buffer); if (i == 0 || i == -1) { break; } buffer.flip(); outC.write(buffer); buffer.clear(); } fis.close(); return baos.toByteArray(); }
Example #10
Source File: FixLenDataParser.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
@Override public void setDataSource(Object inputDataSource) { if (releaseDataSource) releaseDataSource(); byteBuffer.clear(); byteBuffer.flip(); decoder.reset(); bytesProcessed = 0; if (inputDataSource == null) { eof = true; } else { eof = false; if (inputDataSource instanceof ReadableByteChannel) { inChannel = ((ReadableByteChannel)inputDataSource); } else { inChannel = Channels.newChannel((InputStream)inputDataSource); } } }
Example #11
Source File: SchemaUtils.java From DataflowTemplates with Apache License 2.0 | 6 votes |
/** * The {@link SchemaUtils#getGcsFileAsString(String)} reads a file from GCS and returns it as a * string. * * @param filePath path to file in GCS * @return contents of the file as a string * @throws IOException thrown if not able to read file */ public static String getGcsFileAsString(String filePath) { MatchResult result; try { result = FileSystems.match(filePath); checkArgument( result.status() == MatchResult.Status.OK && !result.metadata().isEmpty(), "Failed to match any files with the pattern: " + filePath); List<ResourceId> rId = result.metadata().stream() .map(MatchResult.Metadata::resourceId) .collect(Collectors.toList()); checkArgument(rId.size() == 1, "Expected exactly 1 file, but got " + rId.size() + " files."); Reader reader = Channels.newReader(FileSystems.open(rId.get(0)), StandardCharsets.UTF_8.name()); return CharStreams.toString(reader); } catch (IOException ioe) { LOG.error("File system i/o error: " + ioe.getMessage()); throw new RuntimeException(ioe); } }
Example #12
Source File: ClientNetworkReceiver.java From riiablo with Apache License 2.0 | 6 votes |
@Override protected void processSystem() { InputStream in = socket.getInputStream(); try { if (in.available() > 0) { ReadableByteChannel channel = Channels.newChannel(in); buffer.clear(); int i = channel.read(buffer); buffer.rewind().limit(i); D2GS d2gs = new D2GS(); int p = 0; while (buffer.hasRemaining()) { int size = ByteBufferUtil.getSizePrefix(buffer); D2GS.getRootAsD2GS(ByteBufferUtil.removeSizePrefix(buffer), d2gs); if (DEBUG_PACKET) Gdx.app.debug(TAG, p++ + " packet type " + D2GSData.name(d2gs.dataType()) + ":" + size + "B"); process(d2gs); // System.out.println(buffer.position() + "->" + (buffer.position() + size + 4)); buffer.position(buffer.position() + size + 4); // advance position passed current packet + size prefix of next packet } } } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); } }
Example #13
Source File: DiskStorageService.java From tus-java-server with MIT License | 6 votes |
@Override public InputStream getUploadedBytes(UploadId id) throws IOException, UploadNotFoundException { InputStream inputStream = null; UploadInfo uploadInfo = getUploadInfo(id); if (UploadType.CONCATENATED.equals(uploadInfo.getUploadType()) && uploadConcatenationService != null) { inputStream = uploadConcatenationService.getConcatenatedBytes(uploadInfo); } else { Path bytesPath = getBytesPath(id); //If bytesPath is not null, we know this is a valid Upload URI if (bytesPath != null) { inputStream = Channels.newInputStream(FileChannel.open(bytesPath, READ)); } } return inputStream; }
Example #14
Source File: ML100kRatingPredictionExample.java From JavaFM with Mozilla Public License 2.0 | 6 votes |
public static SimpleListWiseFMData getRecommendationDataset(String file) throws IOException { SimpleListWiseFMData dataset = new SimpleListWiseFMData(NUM_USERS + NUM_ITEMS); if (!new File(file).exists()) { URL url = new URL("http://files.grouplens.org/datasets/movielens/ml-100k/" + file); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } InputStream is = new FileInputStream(file); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { reader.lines().forEach(line -> { String[] tokens = line.split("\t"); int u = parseInt(tokens[0]) - 1; int i = parseInt(tokens[1]) - 1 + NUM_USERS; double r = parseDouble(tokens[2]); dataset.add(new FMInstance(r, new int[]{u, i}, new double[]{1.0, 1.0}), u); }); } return dataset; }
Example #15
Source File: UnixSocket.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
@Override public InputStream getInputStream() throws IOException { if (!channel.isOpen()) { throw new SocketException("Socket is closed"); } if (!channel.isConnected()) { throw new SocketException("Socket is not connected"); } if (inputShutdown) { throw new SocketException("Socket input is shutdown"); } return new FilterInputStream(Channels.newInputStream(channel)) { @Override public void close() throws IOException { shutdownInput(); } }; }
Example #16
Source File: UnixSocket.java From jkube with Eclipse Public License 2.0 | 6 votes |
@Override public InputStream getInputStream() throws IOException { if (!channel.isOpen()) { throw new SocketException("Socket is closed"); } if (!channel.isConnected()) { throw new SocketException("Socket is not connected"); } if (inputShutdown) { throw new SocketException("Socket input is shutdown"); } return new FilterInputStream(Channels.newInputStream(channel)) { @Override public void close() throws IOException { shutdownInput(); } }; }
Example #17
Source File: DataRequest.java From olingo-odata4 with Apache License 2.0 | 6 votes |
private Object getRawValueFromClient() throws DeserializerException { InputStream input = getODataRequest().getBody(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); if (input != null) { try { ByteBuffer inBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); ReadableByteChannel ic = Channels.newChannel(input); WritableByteChannel oc = Channels.newChannel(buffer); while (ic.read(inBuffer) > 0) { inBuffer.flip(); oc.write(inBuffer); inBuffer.rewind(); } return buffer.toByteArray(); } catch (IOException e) { throw new ODataRuntimeException("Error on reading content"); } } return null; }
Example #18
Source File: ODataNettyHandlerImpl.java From olingo-odata4 with Apache License 2.0 | 6 votes |
/** * Copy OData content to netty content * @param input * @param response */ static void copyContent(final ReadableByteChannel input, final HttpResponse response) { try (WritableByteChannel output = Channels.newChannel(new ByteBufOutputStream(((HttpContent)response).content()))){ ByteBuffer inBuffer = ByteBuffer.allocate(COPY_BUFFER_SIZE); while (input.read(inBuffer) > 0) { inBuffer.flip(); output.write(inBuffer); inBuffer.clear(); } closeStream(output); } catch (IOException e) { throw new ODataRuntimeException("Error on reading request content", e); } finally { closeStream(input); } }
Example #19
Source File: TestInterceptor.java From product-microgateway with Apache License 2.0 | 6 votes |
public String getByteChannel(Request request) { try { ByteChannel byteChannel = request.getByteChannel(); InputStream in = Channels.newInputStream(byteChannel); StringBuilder textBuilder = new StringBuilder(); try (Reader reader = new BufferedReader( new InputStreamReader(in, Charset.forName(StandardCharsets.UTF_8.name())))) { int c = 0; while ((c = reader.read()) != -1) { textBuilder.append((char) c); } return textBuilder.toString(); } } catch (InterceptorException | IOException e) { log.error("Error while reading the the byte channel", e); } return ""; }
Example #20
Source File: CdcrTransactionLog.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Re-open the output stream of the tlog and position * the file pointer at the end of the file. It assumes * that the tlog is non-empty and that the tlog's header * has been already read. */ synchronized void reopenOutputStream() { try { if (debug) { log.debug("Re-opening tlog's output stream: {}", this); } raf = new RandomAccessFile(this.tlogFile, "rw"); channel = raf.getChannel(); long start = raf.length(); raf.seek(start); os = Channels.newOutputStream(channel); fos = new FastOutputStream(os, new byte[65536], 0); fos.setWritten(start); // reflect that we aren't starting at the beginning } catch (IOException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e); } }
Example #21
Source File: DelimitedDataParser.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
@Override public void setDataSource(Object inputDataSource) { if (releaseDataSource) releaseDataSource(); decoder.reset();// reset CharsetDecoder dataBuffer.clear(); dataBuffer.flip(); charBuffer.clear(); charBuffer.flip(); recordCounter = 1;// reset record counter bytesProcessed = 0; if (inputDataSource == null) { isEof = true; } else { isEof = false; if (inputDataSource instanceof ReadableByteChannel) { reader = ((ReadableByteChannel)inputDataSource); } else { reader = Channels.newChannel((InputStream)inputDataSource); } } }
Example #22
Source File: ConsoleService.java From jolie with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void run() { try( FileInputStream fis = new FileInputStream( FileDescriptor.in ); BufferedReader stdin = new BufferedReader( new InputStreamReader( Channels.newInputStream( fis.getChannel() ) ) ) ) { String line; while( keepRun ) { line = stdin.readLine(); if( sessionListeners ) { for( String s : sessionTokens.keySet() ) { Value v = Value.create(); v.getFirstChild( "token" ).setValue( s ); v.setValue( line ); sendMessage( CommMessage.createRequest( "in", "/", v ) ); } } else { sendMessage( CommMessage.createRequest( "in", "/", Value.create( line ) ) ); } } } catch( ClosedByInterruptException ce ) { } catch( IOException e ) { interpreter().logWarning( e ); } }
Example #23
Source File: ObservableRedableByteChannelTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * asserts close is reported */ @Test public void testClose() throws IOException { EventLogHttpTransferListener listener = new EventLogHttpTransferListener(); ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream(new byte[10])); ReadableByteChannel in = new ObservableRedableByteChannel(channel, listener); in.close(); assertFalse(in.isOpen()); assertEquals(of(Closed.INSTANCE), listener.getEventLog()); }
Example #24
Source File: InputStreamBenchmark.java From SimpleFlatMapper with MIT License | 5 votes |
@Benchmark public void testFileChannelViaRandomFile(Blackhole blackhole) throws IOException { try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) { try (FileChannel open = randomAccessFile.getChannel()) { try (InputStream inputStream = Channels.newInputStream(open)) { consume(inputStream, blackhole); } } } }
Example #25
Source File: FileUtils.java From android-classyshark with Apache License 2.0 | 5 votes |
private static void obtainNewJarFrom(Release release, File file) throws IOException { URL url = new URL(release.getDownloadURL()); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); }
Example #26
Source File: MavenWrapperDownloader.java From spring-reactive-sample with GNU General Public License v3.0 | 5 votes |
private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); }
Example #27
Source File: MavenWrapperDownloader.java From spring-boot-demo-all with Apache License 2.0 | 5 votes |
private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); }
Example #28
Source File: Playlist.java From AnimeTaste with MIT License | 5 votes |
private static Readable makeReadable(ReadableByteChannel source) { if (source == null) { throw new NullPointerException("source"); } return Channels.newReader(source, java.nio.charset.Charset.defaultCharset().name()); }
Example #29
Source File: FileUtils.java From workcraft with MIT License | 5 votes |
public static void copyFileToStream(File inFile, OutputStream os) throws IOException { FileInputStream is = new FileInputStream(inFile); FileChannel inChannel = is.getChannel(); WritableByteChannel outChannel = Channels.newChannel(os); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (is != null) is.close(); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Example #30
Source File: ChunkedWriteHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testChunkedNioStream() { check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES)))); check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))), new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))), new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES)))); }