简体   繁体   中英

File writing and reading objects using Threads

I have a main thread from which we start two subsequent threads that perform file writing and file reading operations respectively.I have another class called orderDetails with attributes and its getter and setters. The current program runs in such a way that it writes object list to the file in a stretch and reads it back.

QUESTION: I am in need to write the contents of the object(cust1) into a file and read it back from file simultaneously.This has to be performed for all the objects(cust1,cust2) specified. Suggest the possible ways to resolve this.

Main Class

public class MainThread  {
         public static void main(String[] args) throws InterruptedException {
              Thread1 td1=new Thread1();
              Thread2 td2=new Thread2();
              Thread t1=new Thread(td1);
              Thread t2=new Thread(td2);
              t1.start();
              t1.sleep(100);
              t2.start();
        }
    }

orderDetails class- a normal pojo class

 public class orderDetails {
        private String custName;
        private double advancePaid;
        private int mobileModel;
        private boolean replacement;
        private String problemFaced;
        private boolean softwareRequirement;
       public orderDetails(String custName, double advancePaid, int mobileModel,
                boolean replacement, String problemFaced,
                boolean softwareRequirement) {
            super();
            this.custName = custName;
            this.advancePaid = advancePaid;
            this.mobileModel = mobileModel;
            this.replacement = replacement;
            this.problemFaced = problemFaced;
            this.softwareRequirement = softwareRequirement;
        } 
        public boolean isSoftwareRequirement() {
            return softwareRequirement;
        }
        public void setSoftwareRequirement(boolean softwareRequirement) {
            this.softwareRequirement = softwareRequirement;
        }
        public int getMobileModel() {
            return mobileModel;
        }
        public void setMobileModel(int mobileModel) {
            this.mobileModel = mobileModel;
        }
        public String getProblemFaced() {
            return problemFaced;
        }
        public void setProblemFaced(String problemFaced) {
            this.problemFaced = problemFaced;
        }
        public boolean isReplacement() {
            return replacement;
        }
        public void setReplacement(boolean replacement) {
            this.replacement = replacement;
        }
        public double getAdvancePaid() {
            return advancePaid;
        }
        public void setAdvancePaid(double advancePaid) {
            this.advancePaid = advancePaid;
        }
        public String getCustName() {
            return custName;
        }
        public void setCustName(String custName) {
            this.custName = custName;
        }

    }

File Writing-Writes the attributes into the file

 public class FileWriting implements Runnable {
        orderDetails cust1=new orderDetails("vid",2000.00,2543,true,"display",false);
        orderDetails cust2=new orderDetails("kesav",8000.00,7845,false,"battery",true);
        ArrayList<orderDetails> orderArr=new ArrayList<orderDetails>();
         orderDetails obj;
                public void run() {
            orderArr.add(cust1);
            orderArr.add(cust2);
             try {
                for(orderDetails obj:orderArr)
                {
                fileOperations(obj);
                }
            }
                catch (IOException e) {
                    e.printStackTrace();
            }
        }

        public void fileOperations(orderDetails obj) throws IOException{
            File f= new File("C:\\Users\\311518\\Desktop\\threadtest2.txt");
            Calendar calNow = Calendar.getInstance();
            Calendar orderDate;
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            FileWriter fstream;
              if(f.exists()){
                  //append mode
             fstream = new FileWriter(f,true);
              }
              else
              {
                  // to open a new file
              f.createNewFile();
                    // write mode
             fstream = new FileWriter(f,false);
              }
              BufferedWriter out = new BufferedWriter(fstream);
                     out.write(obj.getCustName()+" "+obj.getMobileModel()+" "+obj.getProblemFaced()+" "+obj.getAdvancePaid()+" "+obj.isReplacement()+" "+obj.isSoftwareRequirement());  
                     double balanceAmt=obj.getAdvancePaid()-200;
                     out.write(" "+balanceAmt); 
                     orderDate = (Calendar) calNow.clone();
                     out.write(" "+formatter.format(orderDate.getTime()));
                     orderDate.add(Calendar.DAY_OF_YEAR, + 10);
                     out.write(" "+formatter.format(orderDate.getTime()));
                     out.newLine();
                 out.close();
        }
     }

File Reading class-Reads the attributes from the file

 public class FileReading implements Runnable{
        File f= new File("C:\\Users\\311518\\Desktop\\threadtest2.txt");
        public void run() {
            try {
                readingText();
                System.out.println("Thanks for ur order");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void readingText() throws IOException{
            String [] temp = null;
            FileReader fr = new FileReader(f); 
            BufferedReader br = new BufferedReader(fr); 
            String s; 
            System.out.println("--------ORDER DETAILS------");
             System.out.println("Name Model Adv Prob Replacement S/w Bal OrderDate Deliverdate ");
                while((s = br.readLine()) != null) { 
                                      //display ordered details
                      temp = s.toString().split("\n");
                      for(int i=0;i<temp.length;i++){
                    System.out.println(temp[i]);
                      }
        }

    }
    }

You could try to use a common lock object, put a lock on it when you write and wait for the writing to finish before you read. Example:

Write:

for(orderDetails obj:orderArr)
{
    synchronized(FileWriting.class)
    {
        fileOperations(obj);
    }
    Thread.yield();
}   

Read:

synchronized(FileWriting.class) {
    readingText();
    Thread.yield();
}

Maybe you should also add the reading in a loop and have the writer to signal when it finished writing so the reader can stop.

Perfect case for wait() and notify(), i think.

FileWriting

  1. Build Order details list
  2. Synchronize on this
  3. Write order details to file
  4. notify()
  5. end synchronization block

FileReading

  1. Synchronize on FileWriting
  2. read from file
  3. wait()
  4. do this on a while favoring your order condition
  5. end synchronization block

You can do the above operation similar like below code. perfect use of producer consumer Thread using wait() and notify() .

FileOperator.java

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();
    }
}

and here is our FileReaderWriterDemo.java

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();
    }

}

Output in console:

Going to write

--------ORDER DETAILS------

OrderNo:1 | advancePaid: 2000 | custName: Mr.XXX | mobileModel: Nokia

Please find the below Code Sample....

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;

class MyBuffer{
    transient byte[] bytes = null;
    public int bytesTransmitted = 0;
    private int bufferedBytes = 0;
    public static boolean isWriting = false;
    public static boolean readComplete = false;
    MyBuffer(File srcFile,File desFile){
        try {
            if(!desFile.exists()){desFile.createNewFile();}

            ReadThread  readThrd  = new ReadThread  (this,new RandomAccessFile(srcFile,"r"),"read");
//          ReadThread  readThrd  = new ReadThread  (this,new FileInputStream(srcFile),"read");
//          WriteThread writeThrd = new WriteThread (this,new RandomAccessFile(desFile,"rw"),"write");
            WriteThread writeThrd = new WriteThread (this,new FileOutputStream(desFile),"write");
        } catch (Exception e) {
            e.printStackTrace();
        }       
    }
    public void clearBytes() {
        this.bytes = null;
        this.bytesTransmitted+=this.bufferedBytes;
        this.bufferedBytes=0;
        MyBuffer.isWriting = false;

    }
    public byte[] getBytes() {
        return this.bytes;
    }
    public void setBytes(byte[] bytes) {
        if(bytes!=null){
            if(this.bytes!=null){
                byte[] tempByte = new byte[this.bytes.length+bytes.length];
                System.arraycopy(this.bytes, 0, tempByte, 0, this.bytes.length);
                System.arraycopy(bytes, 0, tempByte, this.bytes.length, bytes.length);
                this.bytes = tempByte;
            }else{
                this.bytes = bytes;
            }
            this.bufferedBytes+=bytes.length;
        }
    }


}
class ReadStreamThread implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
}
class ReadThread implements Runnable{
    private Thread t;
    private RandomAccessFile file=null;
    private FileInputStream fis=null;
    private MyBuffer buffer;

    ReadThread(MyBuffer obj,RandomAccessFile readFile,String threadName) {
        // TODO Auto-generated constructor stub
        this.t = new Thread(this,threadName);
        this.file = readFile;
        this.buffer = obj;
        this.t.start();
    }
    ReadThread(MyBuffer obj,FileInputStream readFis,String threadName) {
        // TODO Auto-generated constructor stub
        this.t = new Thread(this,threadName);
        this.fis = readFis;
        this.buffer = obj;
        this.t.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while(true){
                if(!MyBuffer.isWriting){
                    byte[] b = new byte[10];
                    if(file!=null){
                        if(this.file.length()<=this.buffer.bytesTransmitted){
                            this.buffer.setBytes(null);
                            this.buffer.readComplete = true;
                            break;
                        }
                        this.file.read(b);
                        this.buffer.setBytes(b);
                    }else if(fis!=null){
                        if(this.fis.available()<=this.buffer.bytesTransmitted){
                            this.buffer.setBytes(null);
                            break;
                        }
                        this.fis.read(b);
                        this.buffer.setBytes(b);
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }
}
class WriteThread implements Runnable{
    private Thread t;
    private RandomAccessFile file=null;
    private FileOutputStream fos=null;
    private MyBuffer buffer;

    WriteThread(MyBuffer obj,RandomAccessFile writeFile,String threadName) {
        // TODO Auto-generated constructor stub
        this.t = new Thread(this,threadName);
        this.file = writeFile;
        this.buffer = obj;
        this.t.start();
    }

    WriteThread(MyBuffer obj,FileOutputStream writeFos,String threadName) {
        // TODO Auto-generated constructor stub
        this.t = new Thread(this,threadName);
        this.fos = writeFos;
        this.buffer = obj;
        this.t.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while(true){
                    if(this.buffer.getBytes()!=null){
                        MyBuffer.isWriting = true;
                        if(this.file!=null){
                            this.file.write(this.buffer.getBytes());
                        }else if(this.fos!=null){
                            this.fos.write(this.buffer.getBytes());
                        }
                        this.buffer.clearBytes();
                    }else{
                        if(MyBuffer.readComplete)
                            break;

                        MyBuffer.isWriting = false;
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class ReadWriteModifyMain {
    public static void main(String[] args) {
        new MyBuffer(new File("C:\\Users\\Manoj\\Samples\\Samplers\\src.txt"),new File("C:\\Users\\Manoj\\Samples\\Samplers\\des.txt"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM