Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do the above operation similar like below code. perfect use of producer consumer Thread using <code>wait()</code> and <code>notify()</code>.</p> <p><strong>FileOperator.java</strong></p> <pre><code>public class FileOperator { File file = new File("D:\\Personal\\MyProjects\\File\\file.txt"); BufferedWriter bw; BufferedReader br; boolean isWriteComplete = false; public FileOperator() throws IOException { if(!file.exists()) file.createNewFile(); bw = new BufferedWriter(new FileWriter(file)); br = new BufferedReader(new FileReader(file)); } public void writeInFile(String str) throws IOException{ bw.write(str); bw.newLine(); bw.flush(); } public String readFromFile() throws IOException{ return br.readLine(); } } </code></pre> <p>and here is our <strong>FileReaderWriterDemo.java</strong></p> <pre><code>class ThreadReader implements Runnable{ FileOperator fo; public ThreadReader(FileOperator fo) { super(); this.fo = fo; } @Override public void run() { synchronized (fo) { if(!fo.isWriteComplete){ try { fo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("--------ORDER DETAILS------"); try { System.out.println(fo.readFromFile()); } catch (IOException e) { e.printStackTrace(); } fo.notify(); } } } class ThreadWriter implements Runnable{ FileOperator fo; public ThreadWriter(FileOperator fo) { super(); this.fo = fo; } @Override public void run() { synchronized (fo) { System.out.println("Going to write..."); try { fo.writeInFile("OrderNo:1 | advancePaid: 2000 | custName: Mr.XXX | mobileModel: Nokia"); } catch (IOException e) { e.printStackTrace(); } fo.isWriteComplete = true; fo.notify(); } } } public class FileReaderWriterDemo { public static void main(String[] args) { FileOperator fop = null; try { fop = new FileOperator(); } catch (IOException e) { e.printStackTrace(); } Thread tr = new Thread(new ThreadWriter(fop)); tr.start(); Thread tw = new Thread(new ThreadReader(fop)); tw.start(); } } </code></pre> <p>Output in console:</p> <p>Going to write</p> <p>--------ORDER DETAILS------</p> <p>OrderNo:1 | advancePaid: 2000 | custName: Mr.XXX | mobileModel: Nokia</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload