I am trying to copy a file from my computer to another one on my LAN. My requirement is that there should be some password protection when I run the program so that no one else can send a file even if they manage to run the program.
My server code:
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
servsock = new ServerSocket(SOCKET_PORT);
String FILE_TO_SEND = "D:/Hi.txt";
while (true) {
System.out.println("Waiting...");
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
File myFile = new File(FILE_TO_SEND);
byte[] mybytearray = new byte[(int) myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println("Done.");
}
My client code:
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
String FILE_TO_RECEIVED = "C:/Hey.txt";
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
byte[] mybytearray = new byte[10240];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
This code runs properly and the file is copied without any glitch, and I can also send multiple files across. But I don't know how to make this password protected, so I could use some help here.