android 将手机中文件复制到u盘中

将手机中的文件复制到u盘中,需要u盘读取权限和文件读写权限

1.添加权限

    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

2.添加第三方依赖库

      implementation 'com.github.mjdev:libaums:0.5.5'

3.编写界面

 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android盒子外接U盘文件读写测试DEMO"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        />

    <EditText
        android:id="@+id/u_disk_edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="输入要保存到U盘中的文字内容"/>


    <Button
        android:id="@+id/u_disk_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="往U盘中写入数据"/>

    <Button
        android:id="@+id/u_disk_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="从U盘中读取数据"/>

    <TextView
        android:id="@+id/u_disk_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        />
</LinearLayout>

4.在activity中编写功能

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//输入的内容
private EditText u_disk_edt;
//写入到U盘
private Button u_disk_write;
//从U盘读取
private Button u_disk_read;
//显示读取的内容
private TextView u_disk_show;
//自定义U盘读写权限
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
//当前处接U盘列表
private UsbMassStorageDevice[] storageDevices;
//当前U盘所在文件目录
private UsbFile cFolder;
private final static String U_DISK_FILE_NAME = "u_disk.txt";
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 100:
                showToastMsg("保存成功");
                break;
            case 101:
                String txt = msg.obj.toString();
                if (!TextUtils.isEmpty(txt))
                    u_disk_show.setText("读取到的数据是:" + txt);
                break;
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    initViews();
    registerUDiskReceiver();
}

private void initViews() {
    u_disk_edt = (EditText) findViewById(R.id.u_disk_edt);
    u_disk_write = (Button) findViewById(R.id.u_disk_write);
    u_disk_read = (Button) findViewById(R.id.u_disk_read);
    u_disk_show = (TextView) findViewById(R.id.u_disk_show);
    u_disk_write.setOnClickListener(this);
    u_disk_read.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.u_disk_write:
            final String content = u_disk_edt.getText().toString().trim();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    saveText2UDisk(content);
                }
            });

            break;
        case R.id.u_disk_read:
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    readFromUDisk();
                }
            });

            break;
    }
}

private void readFromUDisk() {
    UsbFile[] usbFiles = new UsbFile[0];
    try {
        usbFiles = cFolder.listFiles();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (null != usbFiles && usbFiles.length > 0) {
        for (UsbFile usbFile : usbFiles) {
            if (usbFile.getName().equals(U_DISK_FILE_NAME)) {
                readTxtFromUDisk(usbFile);
            }
        }
    }
}

/**
 * @description 保存数据到U盘,目前是保存到根目录的
 * @author ldm
 * @time 2017/9/1 17:17
 */
private void saveText2UDisk(String content) {
    //项目中也把文件保存在了SD卡,其实可以直接把文本读取到U盘指定文件
    File file = FileUtil.getSaveFile(getPackageName()
                    + File.separator + FileUtil.DEFAULT_BIN_DIR,
            U_DISK_FILE_NAME);
    try {
        FileWriter fw = new FileWriter(file);
        fw.write(content);
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (null != cFolder) {
        FileUtil.saveSDFile2OTG(file, cFolder);
        mHandler.sendEmptyMessage(100);
    }
}

/**
 * @description OTG广播注册
 * @author ldm
 * @time 2017/9/1 17:19
 */
private void registerUDiskReceiver() {
    //监听otg插入 拔出
    IntentFilter usbDeviceStateFilter = new IntentFilter();
    usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mOtgReceiver, usbDeviceStateFilter);
    //注册监听自定义广播
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mOtgReceiver, filter);
}

/**
 * @description OTG广播,监听U盘的插入及拔出
 * @author ldm
 * @time 2017/9/1 17:20
 * @param
 */
private BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (action) {
            case ACTION_USB_PERMISSION://接受到自定义广播
                UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                //允许权限申请
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (usbDevice != null) {
                        //用户已授权,可以进行读取操作
                        readDevice(getUsbMass(usbDevice));
                    } else {
                        showToastMsg("没有插入U盘");
                    }
                } else {
                    showToastMsg("未获取到U盘权限");
                }
                break;
            case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播
                UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device_add != null) {
                    //接收到U盘插入广播,尝试读取U盘设备数据
                    redUDiskDevsList();
                }
                break;
            case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播
                showToastMsg("U盘已拔出");
                break;
        }
    }
};

/**
 * @description U盘设备读取
 * @author ldm
 * @time 2017/9/1 17:20
 */
private void redUDiskDevsList() {
    //设备管理器
    UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    //获取U盘存储设备
    storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    //一般手机只有1个OTG插口
    for (UsbMassStorageDevice device : storageDevices) {
        //读取设备是否有权限
        if (usbManager.hasPermission(device.getUsbDevice())) {
            readDevice(device);
        } else {
            //没有权限,进行申请
            usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
        }
    }
    if (storageDevices.length == 0) {
        showToastMsg("请插入可用的U盘");
    }
}

private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
    for (UsbMassStorageDevice device : storageDevices) {
        if (usbDevice.equals(device.getUsbDevice())) {
            return device;
        }
    }
    return null;
}

private void readDevice(UsbMassStorageDevice device) {
    try {
        device.init();//初始化
        //设备分区
        Partition partition = device.getPartitions().get(0);
        //文件系统
        FileSystem currentFs = partition.getFileSystem();
        currentFs.getVolumeLabel();//可以获取到设备的标识
        //通过FileSystem可以获取当前U盘的一些存储信息,包括剩余空间大小,容量等等
        Log.e("Capacity: ", currentFs.getCapacity() + "");
        Log.e("Occupied Space: ", currentFs.getOccupiedSpace() + "");
        Log.e("Free Space: ", currentFs.getFreeSpace() + "");
        Log.e("Chunk size: ", currentFs.getChunkSize() + "");
        cFolder = currentFs.getRootDirectory();//设置当前文件对象为根目录
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void showToastMsg(String msg) {
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}

private void readTxtFromUDisk(UsbFile usbFile) {
    UsbFile descFile = usbFile;
    //读取文件内容
    InputStream is = new UsbFileInputStream(descFile);
    //读取秘钥中的数据进行匹配
    StringBuilder sb = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new InputStreamReader(is));
        String read;
        while ((read = bufferedReader.readLine()) != null) {
            sb.append(read);
        }
        Message msg = mHandler.obtainMessage();
        msg.what = 101;
        msg.obj = read;
        mHandler.sendMessage(msg);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
          }
        }
    }
  }

5.添加文件处理工具类

     public class FileUtil {
             public static final String DEFAULT_BIN_DIR = "usb";
        /**
         * 检测SD卡是否存在
         */
        public static boolean checkSDcard() {
            return Environment.MEDIA_MOUNTED.equals(Environment
                    .getExternalStorageState());
        }
    
        /**
         * 从指定文件夹获取文件
         *
         * @return 如果文件不存在则创建, 如果如果无法创建文件或文件名为空则返回null
         */
        public static File getSaveFile(String folderPath, String fileNmae) {
            File file = new File(getSavePath(folderPath) + File.separator
                    + fileNmae);
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }
    
        /**
         * 获取SD卡下指定文件夹的绝对路径
         *
         * @return 返回SD卡下的指定文件夹的绝对路径
         */
        public static String getSavePath(String folderName) {
            return getSaveFolder(folderName).getAbsolutePath();
        }
    
        /**
         * 获取文件夹对象
         *
         * @return 返回SD卡下的指定文件夹对象,若文件夹不存在则创建
         */
        public static File getSaveFolder(String folderName) {
            File file = new File(getExternalStorageDirectory()
                    .getAbsoluteFile()
                    + File.separator
                    + folderName
                    + File.separator);
            file.mkdirs();
            return file;
        }
    
        /**
         * 关闭流
         */
        public static void closeIO(Closeable... closeables) {
            if (null == closeables || closeables.length <= 0) {
                return;
            }
            for (Closeable cb : closeables) {
                try {
                    if (null == cb) {
                        continue;
                    }
                    cb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private static void redFileStream(OutputStream os, InputStream is) throws IOException {
            int bytesRead = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
            os.close();
            is.close();
        }
    
        /**
         * @description 把本地文件写入到U盘中
         * @author ldm
         * @time 2017/8/22 10:22
         */
        public static void saveSDFile2OTG(final File f, final UsbFile usbFile) {
            UsbFile uFile = null;
            FileInputStream fis = null;
            try {//开始写入
                fis = new FileInputStream(f);//读取选择的文件的
                if (usbFile.isDirectory()) {//如果选择是个文件夹
                    UsbFile[] usbFiles = usbFile.listFiles();
                    if (usbFiles != null && usbFiles.length > 0) {
                        for (UsbFile file : usbFiles) {
                            if (file.getName().equals(f.getName())) {
                                file.delete();
                            }
                        }
                    }
                    uFile = usbFile.createFile(f.getName());
                    UsbFileOutputStream uos = new UsbFileOutputStream(uFile);
                    try {
                        redFileStream(uos, fis);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }

6.提示下,要先打开界面,然后把u盘插上手机上,手机才能授权获取到读取u盘的usb读取权限

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容