package elte.java2_utikalauz5.io; import java.io.*; import java.nio.*; import java.nio.channels.*; /** Bufferkezelés. @link.forrásfájl {@docRoot}/../data/io/src SumBuffer2.java @link.letöltés {@docRoot}/../data/io SumBuffer2.jar @since Java 2 Útikalauz programozóknak 5.0 */ public class SumBuffer2 { static double osszeg( ReadableByteChannel in ) throws IOException { double osszeg = 0.0; ByteBuffer buffer = ByteBuffer.allocate(1024); FloatBuffer adatok = buffer.asFloatBuffer(); while ( in.read((ByteBuffer)buffer.clear()) != -1 ) { adatok.position(0).limit(buffer.remaining()/4); while ( adatok.hasRemaining() ) osszeg += adatok.get(); } return osszeg; } public static void main( String[] args ) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024); for ( byte b=0; b<10; ++b ) buffer.put( b ); buffer.position(3).limit(7); ByteBuffer szelet = buffer.slice(); for ( int i=0; i 0 )System.out.print( buffer.get() + " " ); System.out.println(); String fájl = "sum.dat"; { // kiírás FileOutputStream fout = new FileOutputStream(fájl); BufferedOutputStream bout = new BufferedOutputStream(fout); DataOutputStream dout = new DataOutputStream(bout); for( int i=0; i<10; i++ ){ dout.writeFloat((float)i); } dout.close(); } FileInputStream fin = new FileInputStream(fájl); try { FileChannel in = fin.getChannel(); System.out.println("Összeg: "+osszeg(in)); } finally { fin.close(); } } }