Quote:
|
Originally Posted by cfc
[list=1][*]nio probably doesn't have anything as high-level as that, but it should be capable of offering similar functionality with some additional code (detecting '\n' in a CharBuffer I think).
|
NIO doesn't even make it that easy.
Ok, here's the standard IO version
Code:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class SampleFileReader
{
public static void main( String args[] )
{
try
{
File fp = new File( "SomeFileSomewhere.txt" );
FileReader reader = new FileReader( fp );
BufferedReader input = new BufferedReader( reader );
String line;
while( (line = input.readLine()) != null )
{
System.out.println( line );
}
reader.close();
}
catch(Exception e) { e.printStackTrace(); }
}
}
And here's the NIO version. We're just reading in and printing out. If you want "readline" capability, you have to build that in which requires a bit more coding and is slightly more complex. I HIGHLY recommend the standard version for the original poster.
Code:
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.io.FileInputStream;
public class SampleNIOReader
{
public static void main( String args[] )
{
try
{
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
ReadableByteChannel chan = new FileInputStream("someFileSomewhere.txt").getChannel();
ByteBuffer bBuf = ByteBuffer.allocate(1024);
int bytesRead = 0;
while( bytesRead >= 0 )
{
bBuf.rewind();
bytesRead = chan.read( bBuf );
bBuf.flip();
System.out.println( decoder.decode(bBuf).toString() );
}
chan.close();
}
catch( Exception e ) { e.printStackTrace(); }
}
}
** Please note that the above code snips are NOT production quality, but should give you and a good idea as to how to read a file in. In your code, you should do some error handling, etc.