Così si sa che si può utilizzare AsynchronousFileChannel per leggere un intero file in una stringa:Come utilizzare AsynchronousFileChannel da leggere per uno StringBuffer efficiente
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ);
long len = fileChannel.size();
ReadAttachment readAttachment = new ReadAttachment();
readAttachment.byteBuffer = ByteBuffer.allocate((int) len);
readAttachment.asynchronousChannel = fileChannel;
CompletionHandler<Integer, ReadAttachment> completionHandler = new CompletionHandler<Integer, ReadAttachment>() {
@Override
public void completed(Integer result, ReadAttachment attachment) {
String content = new String(attachment.byteBuffer.array());
try {
attachment.asynchronousChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
completeCallback.accept(content);
}
@Override
public void failed(Throwable exc, ReadAttachment attachment) {
exc.printStackTrace();
exceptionError(errorCallback, completeCallback, String.format("error while reading file [%s]: %s", path, exc.getMessage()));
}
};
fileChannel.read(
readAttachment.byteBuffer,
0,
readAttachment,
completionHandler);
Supponiamo che ora, non voglio di destinare un intero ByteBuffer
, ma leggi riga per riga. Potrei usare uno ByteBuffer
di larghezza fissa e continuare a richiamare read
molte volte, copiare sempre e accodare a un StringBuffer fino a quando non arrivo a una nuova riga ... La mia unica preoccupazione è: perché la codifica del file che sto leggendo potrebbe essere multi byte per carattere (qualcosa di UTF), potrebbe accadere che i byte letti finiscano con un carattere incompleto. Come posso essere sicuro di convertire i byte giusti in stringhe e non di incasinare la codifica?
UPDATE: risposta è nel commento della risposta selezionata, ma in pratica punta a CharsetDecoder.
Non utilizzare async I/O per leggere le linee. Non è adatto. Puoi leggere milioni di righe al secondo con 'BufferedReader.readLine().' – EJP
Ho bisogno di operazioni di blocco! – gotch4
Allora perché stai usando I/O asincrono? Questo non è non-bloccante. È un terzo paradigma, dopo aver bloccato e non bloccato. Ma perché pensi che non puoi usare l'I/O di blocco in primo luogo? – EJP