1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| public class UploadUtil {
// 修改为你的服务端 IP 和端口 private static final String SERVER_IP = ServerConfig.SERVER_IP; private static final int SERVER_PORT = ServerConfig.SERVER_PORT;
public static void uploadAllFilesInDirectory(File dir) { if (dir == null || !dir.exists()) return;
if (dir.isFile()) { try { FileSender.sendFileFold(SERVER_IP, SERVER_PORT, dir); } catch (Exception e) { e.printStackTrace(); } } else if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File f : files) { uploadAllFilesInDirectory(f); // 递归上传 } } } } }
public class FileSender { //按照单文件传输到服务器 public static void send(String host, int port, File file) throws Exception { try (Socket socket = new Socket(host, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); FileInputStream fis = new FileInputStream(file)) {
byte[] nameBytes = file.getName().getBytes("UTF-8"); dos.writeInt(nameBytes.length); dos.write(nameBytes); dos.writeLong(file.length());
byte[] buffer = new byte[4096]; int len; while ((len = fis.read(buffer)) > 0) { dos.write(buffer, 0, len); } dos.flush(); } }
//根据文件目录上传 public static void sendFileFold(String serverIp, int port, File file) throws Exception { try (Socket socket = new Socket(serverIp, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); FileInputStream fis = new FileInputStream(file)) {
// 获取根目录(一般是 /storage/emulated/0) String root = "/storage/emulated/0"; String absPath = file.getAbsolutePath();
// 相对路径(如 Download/abc.jpg) String relativePath = absPath.startsWith(root) ? absPath.substring(root.length() + 1) : file.getName();
// 发送文件名长度和路径名(UTF-8 编码) byte[] nameBytes = relativePath.getBytes("UTF-8"); dos.writeInt(nameBytes.length); dos.write(nameBytes);
// 发送文件大小 dos.writeLong(file.length());
// 发送文件内容 byte[] buffer = new byte[4096]; int len; while ((len = fis.read(buffer)) != -1) { dos.write(buffer, 0, len); }
dos.flush(); System.out.println("文件发送完成: " + relativePath); } }
}
|