您可以通过多种方式执行此操作,建议您向服务器创建一个单独的请求类型,以接受文件名和文件位置(即文件在文件中连接失败的位置)。
这就是从客户端的服务器获取文件的方式:
int filePosition = 0;InputStream is = clientSocket.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();do { baos.write(mybytearray); bytesRead = is.read(mybytearray); if(bytesRead != -1) filePosition += bytesRead;}while (bytesRead != -1);现在,如果由于某种原因连接中断,您可以使用相同的文件名和 filePosition 再次向服务器发送请求,服务器将像下面这样发送文件:
OutputStream outToClient = socke.getOutputStream();// The file name needs to come from the client which will be put in here belowFile myfile = new File("D:\ "+file_name);byte[] mybytearray = new byte[(int) myfile.length()];BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myfile));bis.skip(filePosition) //Advance the stream to the desired location in the filebis.read(mybytearray, 0, mybytearray.length);outToClient.write(mybytearray, 0, mybytearray.length);System.out.println("Arrays on server:"+Arrays.toString(mybytearray));outToClient.flush();bis.close();在客户端中,您可以打开文件流,并
append = true在构造函数中指定如下所示:
FileOutputStream fos = new FileOutputStream("D:\ "+file_name, true);这可能是实现此目的的一种方法,还有很多选择。我还建议在传输后使用诸如MD5之类的哈希函数来验证文件,例如,它为给定的输入创建唯一的标记,并且对于相同的输入始终输出相同的结果,这意味着您可以从同一文件创建标记在服务器和客户端中,如果文件确实相同,它将生成相同的标记。由于图章的大小相对于它自己的文件来说很小,并且它也是固定的,因此可以在客户端/服务器之间发送它而没有太多开销。
您可以使用以下代码生成MD5哈希值:
MessageDigest md = MessageDigest.getInstance("MD5");try (InputStream is = Files.newInputStream(Paths.get("file.txt"))) { DigestInputStream dis = new DigestInputStream(is, md); }byte[] digest = md.digest();


