List of usage examples for java.nio.channels FileChannel read
public final long read(ByteBuffer[] dsts) throws IOException
From source file:MainClass.java
public static void main(String[] args) { File aFile = new File("data.dat"); FileInputStream inFile = null; try {/*from w w w .ja va 2 s. co m*/ inFile = new FileInputStream(aFile); } catch (FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); final int COUNT = 6; ByteBuffer buf = ByteBuffer.allocate(8 * COUNT); long[] data = new long[COUNT]; try { int pos = 0; while (inChannel.read(buf) != -1) { try { ((ByteBuffer) (buf.flip())).asLongBuffer().get(data); pos = data.length; } catch (BufferUnderflowException e) { LongBuffer longBuf = buf.asLongBuffer(); pos = longBuf.remaining(); longBuf.get(data, 0, pos); } System.out.println(); for (int i = 0; i < pos; i++) { System.out.printf("%10d", data[i]); } buf.clear(); } System.out.println("\nEOF reached."); inFile.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(1); } }
From source file:ExplicitChannelRead.java
public static void main(String args[]) { FileInputStream fIn;/* www. j a v a 2s .co m*/ FileChannel fChan; long fSize; ByteBuffer mBuf; try { fIn = new FileInputStream("test.txt"); fChan = fIn.getChannel(); fSize = fChan.size(); mBuf = ByteBuffer.allocate((int) fSize); fChan.read(mBuf); mBuf.rewind(); for (int i = 0; i < fSize; i++) System.out.print((char) mBuf.get()); fChan.close(); fIn.close(); } catch (IOException exc) { System.out.println(exc); System.exit(1); } }
From source file:MainClass.java
public static void main(String args[]) { FileInputStream fIn;/*from w ww . jav a2 s . c om*/ FileChannel fChan; long fSize; ByteBuffer mBuf; try { fIn = new FileInputStream("test.txt"); fChan = fIn.getChannel(); fSize = fChan.size(); mBuf = ByteBuffer.allocate((int) fSize); fChan.read(mBuf); mBuf.rewind(); for (int i = 0; i < fSize; i++) System.out.print((char) mBuf.get()); fChan.close(); fIn.close(); } catch (IOException exc) { System.out.println(exc); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data2.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(24); // More than needed buff.asCharBuffer().put("Some text"); fc.write(buff);/*from w w w .j a v a 2 s. co m*/ fc.close(); fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); }
From source file:BufferToText.java
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data2.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes())); fc.close();// w w w.j a va 2 s .c o m fc = new FileInputStream("data2.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); // Doesn't work: System.out.println(buff.asCharBuffer()); // Decode using this system's default Charset: buff.rewind(); String encoding = System.getProperty("file.encoding"); System.out.println("Decoded using " + encoding + ": " + Charset.forName(encoding).decode(buff)); // Or, we could encode with something that will print: fc = new FileOutputStream("data2.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE"))); fc.close(); // Now try reading again: fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); // Use a CharBuffer to write through: fc = new FileOutputStream("data2.txt").getChannel(); buff = ByteBuffer.allocate(24); // More than needed buff.asCharBuffer().put("Some text"); fc.write(buff); fc.close(); // Read and display: fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); }
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();// w w w.jav a 2 s . c om outChannel.write(buffer); buffer.compact(); } inChannel.close(); outChannel.close(); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data2.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE"))); fc.close();/*w w w.j ava 2s.c o m*/ ByteBuffer buff = ByteBuffer.allocate(BSIZE); // Now try reading again: fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); }
From source file:GetChannel.java
public static void main(String[] args) throws Exception { // Write a file: FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close();//w w w . ja va2 s . co m // Add to the end of the file: fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); // Move to the end fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); // Read the file: fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); }
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 a v a 2 s .c om } 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:Lock.java
public static void main(String args[]) throws IOException, InterruptedException { RandomAccessFile file = null; // The file we'll lock FileChannel f = null; // The channel to the file FileLock lock = null; // The lock object we hold try { // The finally clause closes the channel and releases the lock // We use a temporary file as the lock file. String tmpdir = System.getProperty("java.io.tmpdir"); String filename = Lock.class.getName() + ".lock"; File lockfile = new File(tmpdir, filename); // Create a FileChannel that can read and write that file. // Note that we rely on the java.io package to open the file, // in read/write mode, and then just get a channel from it. // This will create the file if it doesn't exit. We'll arrange // for it to be deleted below, if we succeed in locking it. file = new RandomAccessFile(lockfile, "rw"); f = file.getChannel();/*ww w . j a v a 2 s . c o m*/ // Try to get an exclusive lock on the file. // This method will return a lock or null, but will not block. // See also FileChannel.lock() for a blocking variant. lock = f.tryLock(); if (lock != null) { // We obtained the lock, so arrange to delete the file when // we're done, and then write the approximate time at which // we'll relinquish the lock into the file. lockfile.deleteOnExit(); // Just a temporary file // First, we need a buffer to hold the timestamp ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes // Put the time in the buffer and flip to prepare for writing // Note that many Buffer methods can be "chained" like this. bytes.putLong(System.currentTimeMillis() + 10000).flip(); f.write(bytes); // Write the buffer contents to the channel f.force(false); // Force them out to the disk } else { // We didn't get the lock, which means another instance is // running. First, let the user know this. System.out.println("Another instance is already running"); // Next, we attempt to read the file to figure out how much // longer the other instance will be running. Since we don't // have a lock, the read may fail or return inconsistent data. try { ByteBuffer bytes = ByteBuffer.allocate(8); f.read(bytes); // Read 8 bytes from the file bytes.flip(); // Flip buffer before extracting bytes long exittime = bytes.getLong(); // Read bytes as a long // Figure out how long that time is from now and round // it to the nearest second. long secs = (exittime - System.currentTimeMillis() + 500) / 1000; // And tell the user about it. System.out.println("Try again in about " + secs + " seconds"); } catch (IOException e) { // This probably means that locking is enforced by the OS // and we were prevented from reading the file. } // This is an abnormal exit, so set an exit code. System.exit(1); } // Simulate a real application by sleeping for 10 seconds. System.out.println("Starting..."); Thread.sleep(10000); System.out.println("Exiting."); } finally { // Always release the lock and close the file // Closing the RandomAccessFile also closes its FileChannel. if (lock != null && lock.isValid()) lock.release(); if (file != null) file.close(); } }