How to use Java nio. channels. Filechannel reads ByteBuffer and implements similar behavior similar to BufferedReader #readline()
I want to use Java nio. channels. Filechannel to read the file, but I want to read each line, just like BufferedReader #readline() The reason why I need to use Java nio. channels. Filechannel instead of Java IO is because I need to lock the file and read it line by line from the locked file So I forced the use of Java nio. channels. FileChannel. Please help
Edit this is my code trying to use FileInputStream to get filechannel
public static void main(String[] args){ File file = new File("C:\\dev\\harry\\data.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(); } } }
When the code is here, lock = channel lock();, It immediately goes to finally and lock is still null, so lock Release() generates NullPointerException I don't know why?
Solution
The reason is that you need to use fileoutpustream instead of 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(); }
This code is very good for me
NullPointerException actually hides the real exception, notwritablechannelexception For locking, I think we need to use OutputStream instead of InputStream