Skip to content
Snippets Groups Projects
Select Git revision
  • ef10b95beea4e41a78ece608e18ac7f7e07d6e06
  • master default protected
2 results

StoreThread.java

Blame
  • StoreThread.java 1.45 KiB
    import java.io.*;
    import java.net.Socket;
    
    public class StoreThread implements Runnable{
    
        private final PrintWriter controller;
        private final String filePath;
        private final String fileName;
        private final InputStream in;
        private final OutputStream out;
        private final Socket client;
    
        public StoreThread(PrintWriter co, String p, String n, InputStream i, OutputStream o, Socket c) {
            controller = co;
            filePath = p;
            fileName = n;
            in = i;
            out = o;
            client = c;
        }
    
        @Override
        public void run() {
            try {
                //Send ACK to client
                out.write("ACK".getBytes());
    
                //Prepare to write to file
                File outputFile = new File(filePath+fileName);
                FileOutputStream fileOutput = new FileOutputStream(outputFile);
    
                //Prepare new buffer for data from client
                byte[] buf = new byte[1000];
                int bufLen;
    
                //Wait for receipt of new data
                while((bufLen = in.read(buf)) != -1) {
                    fileOutput.write(buf,0,bufLen);
                }
    
                //Send completion ack to controller
                controller.write("STORE_ACK "+fileName);
    
                //Close file output
                fileOutput.close();
    
                //Close streams
                in.close();
                out.close();
                client.close();
            }catch (Exception e){
                System.out.println("error "+e);
            }
        }
    }