如何在adb pull传输时自动重命名过长文件名?
解决ADB Pull因Windows长路径限制中断的自动重命名方案
方法1:ADB Shell批量预处理手机端长文件名
先在手机端把过长的文件名截断,从源头避免路径过长问题:
- 连接设备后,进入目标备份目录(以
/sdcard/DCIM为例):adb shell cd /sdcard/DCIM - 执行批量重命名命令,将超过50字符的文件名截断为42字符,加3位随机后缀和省略号(避免重名覆盖):
find . -type f -name "*" | while read file; do fname=$(basename "$file") fpath=$(dirname "$file") if [ ${#fname} -gt 50 ]; then name_part="${fname%.*}" ext_part="${fname##*.}" new_fname="${name_part:0:42}_$(date +%N | cut -c1-3)....$ext_part" mv "$file" "$fpath/$new_fname" fi done - 退出shell后执行拉取:
exit adb pull /sdcard/DCIM D:\Backup\DCIM
方法2:Python脚本拉取时实时重命名本地文件
通过Python遍历手机文件系统,逐个拉取并在本地自动截断长文件名,同时保留原目录结构:
import os import subprocess def pull_with_rename(remote_root, local_root, max_filename_length=45): os.makedirs(local_root, exist_ok=True) # 获取手机端所有文件的绝对路径 adb_cmd = ["adb", "shell", f"find {remote_root} -type f"] remote_files = subprocess.run(adb_cmd, capture_output=True, text=True).stdout.strip().split("\n") for remote_file in remote_files: if not remote_file: continue # 拆分远程文件的路径和文件名 remote_dir, remote_name = os.path.split(remote_file) # 计算本地路径的可用字符数(Windows最大260) local_base_path = os.path.abspath(os.path.join(local_root, os.path.relpath(remote_dir, remote_root))) available_chars = 260 - len(local_base_path) - 1 # 减1是路径分隔符 # 生成短文件名 if len(remote_name) > available_chars: name, ext = os.path.splitext(remote_name) # 预留空间给省略号和扩展名 truncate_len = min(available_chars - len(ext) - 3, max_filename_length) new_name = f"{name[:truncate_len]}...{ext}" else: new_name = remote_name # 构建本地文件路径并创建目录 local_file = os.path.join(local_base_path, new_name) os.makedirs(os.path.dirname(local_file), exist_ok=True) # 执行拉取 subprocess.run(["adb", "pull", remote_file, local_file], check=False) print(f"处理完成: {remote_file} -> {local_file}") # 配置参数后运行 if __name__ == "__main__": REMOTE_BACKUP_DIR = "/sdcard/你的备份目录" LOCAL_SAVE_DIR = r"D:\Backup" pull_with_rename(REMOTE_BACKUP_DIR, LOCAL_SAVE_DIR)
- 注意:确保ADB已添加到系统环境变量,或者在代码中指定ADB的绝对路径;如果担心重名,可以在
new_name中加入时间戳或计数器。
方法3:直接启用Windows长路径支持(无需重命名)
如果不想修改文件名,直接关闭Windows的260字符路径限制:
- 按
Win+R输入regedit打开注册表编辑器 - 导航到
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem - 找到
LongPathsEnabled(没有就右键新建DWORD(32位)值并命名),修改数值为1 - 重启电脑后生效,之后ADB Pull即可正常处理长路径文件
内容的提问来源于stack exchange,提问作者POWBlock
相关产品推荐
相关产品推荐

