我正在尝试将文件从我的计算机复制到LAN上的另一个文件。我的要求是,当我运行程序时应该有一些密码保护,这样即使他们设法运行程序也没有其他人可以发送文件。
我的服务器代码:
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.");
}
我的客户代码:
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)");
此代码运行正常,文件复制没有任何故障,我也可以发送多个文件。但是我不知道如何保护这个密码,所以我可以在这里使用一些帮助。