List of usage examples for java.nio ByteBuffer compact
public abstract ByteBuffer compact();
From source file:Main.java
public static void main(String[] argv) throws Exception { ByteBuffer bbuf = ByteBuffer.allocate(10); int capacity = bbuf.capacity(); // 10 System.out.println(capacity); bbuf.putShort(2, (short) 123); ByteBuffer bb = bbuf.compact(); System.out.println(Arrays.toString(bb.array())); }
From source file:Main.java
public static void main(String[] args) throws Exception { File aFile = new File("primes.txt"); FileInputStream inFile = new FileInputStream(aFile); FileChannel inChannel = inFile.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(1024); buf.position(buf.limit());/*from w w w . j a v a2 s.c o m*/ while (true) { if (buf.remaining() < 8) { if (inChannel.read(buf.compact()) == -1) { break; } buf.flip(); } int strLength = (int) buf.getDouble(); if (buf.remaining() < 2 * strLength) { if (inChannel.read(buf.compact()) == -1) { break; } buf.flip(); } byte[] strChars = new byte[2 * strLength]; buf.get(strChars); if (buf.remaining() < 8) { if (inChannel.read(buf.compact()) == -1) { break; } buf.flip(); } System.out.println(strLength); System.out.println(ByteBuffer.wrap(strChars).asCharBuffer()); System.out.println(buf.getLong()); } inFile.close(); }
From source file:MainClass.java
public static void main(String[] args) throws IOException { FileInputStream inFile = new FileInputStream(args[0]); FileOutputStream outFile = new FileOutputStream(args[1]); FileChannel inChannel = inFile.getChannel(); FileChannel outChannel = outFile.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); int bytesRead = 0; while (bytesRead >= 0 || buffer.hasRemaining()) { if (bytesRead != -1) bytesRead = inChannel.read(buffer); buffer.flip();/*from w w w .j a va2 s.c o m*/ outChannel.write(buffer); buffer.compact(); } inChannel.close(); outChannel.close(); }
From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java
public static void main(String[] args) { // Ensure we have a path to the binary file if (args.length != 1) { logger.info("Please provide the path to a file containing a binary LOOP packet."); System.exit(1);// ww w . j ava 2 s . c o m } else { try { // open and read the file File packetFile = new File(args[0]); FileInputStream fis = new FileInputStream(packetFile); FileChannel fileChannel = fis.getChannel(); ByteBuffer inBuffer = ByteBuffer.allocateDirect(8192); ByteBuffer packetBuffer = ByteBuffer.allocateDirect(8192); while (fileChannel.read(inBuffer) != -1 || inBuffer.position() > 0) { inBuffer.flip(); packetBuffer.put(inBuffer.get()); inBuffer.compact(); } fileChannel.close(); fis.close(); packetBuffer.put(inBuffer.get()); // create an instance of the parser, and report the field contents after parsing DavisWxParser davisWxParser = new DavisWxParser(packetBuffer); // Set up a simple logger that logs to the console PropertyConfigurator.configure(davisWxParser.getLogConfigurationFile()); logger.info("loopID: " + davisWxParser.getLoopID()); logger.info("barTrend: " + davisWxParser.getBarTrend()); logger.info("barTrendAsString: " + davisWxParser.getBarTrendAsString()); logger.info("packetType: " + davisWxParser.getPacketType()); logger.info("nextRecord: " + davisWxParser.getNextRecord()); logger.info("barometer: " + davisWxParser.getBarometer()); logger.info("insideTemperature: " + davisWxParser.getInsideTemperature()); logger.info("insideHumidity: " + davisWxParser.getInsideHumidity()); logger.info("outsideTemperature: " + davisWxParser.getOutsideTemperature()); logger.info("windSpeed: " + davisWxParser.getWindSpeed()); logger.info("tenMinuteAverageWindSpeed: " + davisWxParser.getTenMinuteAverageWindSpeed()); logger.info("windDirection: " + davisWxParser.getWindDirection()); logger.info( "extraTemperatures: " + Arrays.toString(davisWxParser.getExtraTemperatures())); logger.info( "soilTemperatures: " + Arrays.toString(davisWxParser.getSoilTemperatures())); logger.info( "leafTemperatures: " + Arrays.toString(davisWxParser.getLeafTemperatures())); logger.info("outsideHumidity: " + davisWxParser.getOutsideHumidity()); logger.info( "extraHumidities: " + Arrays.toString(davisWxParser.getExtraHumidities())); logger.info("rainRate: " + davisWxParser.getRainRate()); logger.info("uvRadiation: " + davisWxParser.getUvRadiation()); logger.info("solarRadiation: " + davisWxParser.getSolarRadiation()); logger.info("stormRain: " + davisWxParser.getStormRain()); logger.info("currentStormStartDate: " + davisWxParser.getCurrentStormStartDate()); logger.info("dailyRain: " + davisWxParser.getDailyRain()); logger.info("monthlyRain: " + davisWxParser.getMonthlyRain()); logger.info("yearlyRain: " + davisWxParser.getYearlyRain()); logger.info("dailyEvapoTranspiration: " + davisWxParser.getDailyEvapoTranspiration()); logger.info("monthlyEvapoTranspiration: " + davisWxParser.getMonthlyEvapoTranspiration()); logger.info("yearlyEvapoTranspiration: " + davisWxParser.getYearlyEvapoTranspiration()); logger.info("soilMoistures: " + Arrays.toString(davisWxParser.getSoilMoistures())); logger.info("leafWetnesses: " + Arrays.toString(davisWxParser.getLeafWetnesses())); logger.info("insideAlarm: " + davisWxParser.getInsideAlarm()); logger.info("rainAlarm: " + davisWxParser.getRainAlarm()); logger.info("outsideAlarms: " + davisWxParser.getOutsideAlarms()); logger.info("extraTemperatureHumidityAlarms: " + davisWxParser.getExtraTemperatureHumidityAlarms()); logger.info("soilLeafAlarms: " + davisWxParser.getSoilLeafAlarms()); logger.info("transmitterBatteryStatus: " + davisWxParser.getTransmitterBatteryStatus()); logger.info("consoleBatteryVoltage: " + davisWxParser.getConsoleBatteryVoltage()); logger.info("forecastIconValues: " + davisWxParser.getForecastAsString()); logger.info("forecastRuleNumber: " + davisWxParser.getForecastRuleNumberAsString()); logger.info("timeOfSunrise: " + davisWxParser.getTimeOfSunrise()); logger.info("timeOfSunset: " + davisWxParser.getTimeOfSunset()); logger.info("recordDelimiter: " + davisWxParser.getRecordDelimiterAsHexString()); logger.info("crcChecksum: " + davisWxParser.getCrcChecksum()); } catch (java.io.FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (java.io.IOException ioe) { ioe.printStackTrace(); } } }
From source file:HttpGet.java
public static void main(String[] args) { SocketChannel server = null; // Channel for reading from server FileOutputStream outputStream = null; // Stream to destination file WritableByteChannel destination; // Channel to write to it try { // Exception handling and channel closing code follows this block // Parse the URL. Note we use the new java.net.URI, not URL here. URI uri = new URI(args[0]); // Now query and verify the various parts of the URI String scheme = uri.getScheme(); if (scheme == null || !scheme.equals("http")) throw new IllegalArgumentException("Must use 'http:' protocol"); String hostname = uri.getHost(); int port = uri.getPort(); if (port == -1) port = 80; // Use default port if none specified String path = uri.getRawPath(); if (path == null || path.length() == 0) path = "/"; String query = uri.getRawQuery(); query = (query == null) ? "" : '?' + query; // Combine the hostname and port into a single address object. // java.net.SocketAddress and InetSocketAddress are new in Java 1.4 SocketAddress serverAddress = new InetSocketAddress(hostname, port); // Open a SocketChannel to the server server = SocketChannel.open(serverAddress); // Put together the HTTP request we'll send to the server. String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request "Host: " + hostname + "\r\n" + // Required in HTTP 1.1 "Connection: close\r\n" + // Don't keep connection open "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank // line // indicates // end of // request // headers // Now wrap a CharBuffer around that request string CharBuffer requestChars = CharBuffer.wrap(request); // Get a Charset object to encode the char buffer into bytes Charset charset = Charset.forName("ISO-8859-1"); // Use the charset to encode the request into a byte buffer ByteBuffer requestBytes = charset.encode(requestChars); // Finally, we can send this HTTP request to the server. server.write(requestBytes);//from w ww. j a v a 2 s .c o m // Set up an output channel to send the output to. if (args.length > 1) { // Use a specified filename outputStream = new FileOutputStream(args[1]); destination = outputStream.getChannel(); } else // Or wrap a channel around standard out destination = Channels.newChannel(System.out); // Allocate a 32 Kilobyte byte buffer for reading the response. // Hopefully we'll get a low-level "direct" buffer ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024); // Have we discarded the HTTP response headers yet? boolean skippedHeaders = false; // The code sent by the server int responseCode = -1; // Now loop, reading data from the server channel and writing it // to the destination channel until the server indicates that it // has no more data. while (server.read(data) != -1) { // Read data, and check for end data.flip(); // Prepare to extract data from buffer // All HTTP reponses begin with a set of HTTP headers, which // we need to discard. The headers end with the string // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already // skipped them then do so now. if (!skippedHeaders) { // First, though, read the HTTP response code. // Assume that we get the complete first line of the // response when the first read() call returns. Assume also // that the first 9 bytes are the ASCII characters // "HTTP/1.1 ", and that the response code is the ASCII // characters in the following three bytes. if (responseCode == -1) { responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0') + 1 * (data.get(11) - '0'); // If there was an error, report it and quit // Note that we do not handle redirect responses. if (responseCode < 200 || responseCode >= 300) { System.err.println("HTTP Error: " + responseCode); System.exit(1); } } // Now skip the rest of the headers. try { for (;;) { if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13) && (data.get() == 10)) { skippedHeaders = true; break; } } } catch (BufferUnderflowException e) { // If we arrive here, it means we reached the end of // the buffer and didn't find the end of the headers. // There is a chance that the last 1, 2, or 3 bytes in // the buffer were the beginning of the \r\n\r\n // sequence, so back up a bit. data.position(data.position() - 3); // Now discard the headers we have read data.compact(); // And go read more data from the server. continue; } } // Write the data out; drain the buffer fully. while (data.hasRemaining()) destination.write(data); // Now that the buffer is drained, put it into fill mode // in preparation for reading more data into it. data.clear(); // data.compact() also works here } } catch (Exception e) { // Report any errors that arise System.err.println(e); System.err.println("Usage: java HttpGet <URL> [<filename>]"); } finally { // Close the channels and output file stream, if needed try { if (server != null && server.isOpen()) server.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { } } }
From source file:Main.java
public static void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(CAPACITY); while (src.read(buffer) != -1) { buffer.flip();/*from w w w. j ava2 s . c om*/ dest.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { dest.write(buffer); } }
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();//from ww w. ja v a2 s .c o m bytesWritten += wbc.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { bytesWritten += wbc.write(buffer); } rbc.close(); wbc.close(); return bytesWritten; }
From source file:org.carlspring.strongbox.storage.metadata.nuget.TempNupkgFile.java
/** * Copies data from one channel to another * * @param src/* w w w . j av a 2 s .c om*/ * channel source * @param dest * destination channel * @throws IOException * input / output error */ private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { buffer.flip(); dest.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:Main.java
public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();/*from ww w. j av a2 s. c o m*/ // write to the channel, may block dest.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing recycle() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:com.msr.dnsdemo.network.DownloadFile.java
public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException, NullPointerException { if (src != null && dest != null) { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();// w w w. ja v a 2 s. c o m // write to the channel, may block dest.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } } }