Quote:
Originariamente inviato da Frank1962
ps: secondo voi questo tipo di lettura di un file di testo è efficente o c'è qualcosa di meglio?
|
I FileChannel sono dichiarati "più meglio del meglio", però se il file è piccolo la differenza non penso si veda.
Codice:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class NIOReader {
public static void main(String[] args) {
try {
StringBuffer text = new StringBuffer();
FileChannel inChannel = new FileInputStream("z:/prova.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder charsetDecoder = charset.newDecoder();
while( inChannel.read(buffer) != -1 ) {
buffer.flip();
text.append(charsetDecoder.decode(buffer).toString());
buffer.clear();
}
inChannel.close();
System.out.println(text);
} catch(IOException e) {
e.printStackTrace(System.err);
System.out.println("End of stack trace");
}
System.exit(0);
}
}