I am trying to read the binary files using streams and sockets in java but was not able to open the file after reading and copying in the destination.
Please have a look at the code and suggest me the possible solution. I am sending a file from admin side to server.so,that the file will be saved on file system.
Please do not mark as duplicate as i was not able to find the solution anywhere Server side program
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class N {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(4567);
File myFile = new File("C:/Users/rp00491429/Downloads/greatdeepak.mp4");
System.out.println("Waiting for connection");
Socket sock = servsock.accept();
System.out.println("connected");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis=(FileInputStream)sock.getInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray);
for(byte e:mybytearray) {
System.out.print(e);
}
System.out.println(mybytearray.length);
File f=new File("C:/Users/rp00491429/Downloads/dfgd.mp4");
FileOutputStream os = new FileOutputStream(f);
BufferedOutputStream bos=new BufferedOutputStream(os);
bos.write(mybytearray);
os.flush();
sock.close();
}}
Client side program
public static void main(String[] ar) {
try {
Socket socket=new Socket("localhost",4567);
File file=new
File("C:\\Users\\rp00491429\\Downloads\\greatdeepak.mp4");
byte b[]=new byte[(int)file.length()];
FileInputStream fis=new FileInputStream(file);
fis.read(b);
FileOutputStream fos=(FileOutputStream) socket.getOutputStream();
fos.write(b);
} catch (Exception e) {
}
I was able to store the file in the path but not able to open. please have a look at the screenshotdfgd.mp4 in file system but not able to open