如何使用java.nio.channels.FileChannel读取ByteBuffer实现类似B
发布时间:2020-12-15 02:26:19 所属栏目:Java 来源:网络整理
导读:我想使用 java.nio.channels.FileChannel来读取文件,但我想读取每行的行,就像BufferedReader#readLine()一样.我之所以需要使用java.nio.channels.FileChannel而不是java.io是因为我需要对文件进行锁定,并从该锁定文件中逐行读取.所以我强行使用java.nio.chan
我想使用
java.nio.channels.FileChannel来读取文件,但我想读取每行的行,就像BufferedReader#readLine()一样.我之所以需要使用java.nio.channels.FileChannel而不是java.io是因为我需要对文件进行锁定,并从该锁定文件中逐行读取.所以我强行使用java.nio.channels.FileChannel.请帮忙
编辑这是我的代码试图使用FileInputStream来获取FileChannel public static void main(String[] args){ File file = new File("C:devharrydata.txt"); FileInputStream inputStream = null; BufferedReader bufferedReader = null; FileChannel channel = null; FileLock lock = null; try{ inputStream = new FileInputStream(file); channel = inputStream.getChannel(); lock = channel.lock(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String data; while((data = bufferedReader.readLine()) != null){ System.out.println(data); } }catch(IOException e){ e.printStackTrace(); }finally{ try { lock.release(); channel.close(); if(bufferedReader != null) bufferedReader.close(); if(inputStream != null) inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } 当代码在这里时,lock = channel.lock();,它会立即转到finally并且lock仍为null,因此lock.release()会生成NullPointerException.我不知道为什么. 解决方法
原因是您需要使用FileOutpuStream而不是FileInputStream.
请尝试以下代码: FileOutputStream outStream = null; BufferedWriter bufWriter = null; FileChannel channel = null; FileLock lock = null; try{ outStream = new FileOutputStream(file); channel = outStream.getChannel(); lock = channel.lock(); bufWriter = new BufferedWriter(new OutputStreamWriter(outStream)); }catch(IOException e){ e.printStackTrace(); } 这段代码对我来说很好. NUllPointerException实际上隐藏了真正的异常,即NotWritableChannelException.对于锁定,我认为我们需要使用OutputStream而不是InputStream. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |