要将文件从安卓设备保存到USB驱动器,可以使用以下代码示例:
-
确保您的设备已连接到USB驱动器,并且您已经获取了访问USB设备的权限。
-
在您的Android项目中的AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 在您的代码中,您可以使用以下方法将文件从安卓设备复制到USB驱动器:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class MainActivity extends AppCompatActivity {
private static final String USB_DRIVE_PATH = "/mnt/usb_storage/USB_DISK0/";
private void copyFileToUsbDrive(String sourceFilePath, String destinationFileName) {
File sourceFile = new File(sourceFilePath);
File usbDriveDirectory = new File(USB_DRIVE_PATH);
if (!usbDriveDirectory.exists()) {
usbDriveDirectory.mkdirs();
}
File destinationFile = new File(usbDriveDirectory, destinationFileName);
FileChannel sourceChannel = null;
FileChannel destinationChannel = null;
try {
sourceChannel = new FileInputStream(sourceFile).getChannel();
destinationChannel = new FileOutputStream(destinationFile).getChannel();
destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (sourceChannel != null) {
sourceChannel.close();
}
if (destinationChannel != null) {
destinationChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 调用
copyFileToUsbDrive
方法,将文件从设备复制到USB驱动器。传递源文件路径和目标文件名作为参数。
String sourceFilePath = "/storage/emulated/0/Download/source.txt";
String destinationFileName = "destination.txt";
copyFileToUsbDrive(sourceFilePath, destinationFileName);
请注意,USB驱动器的路径可能因设备而异。在上述示例中,我们使用了/mnt/usb_storage/USB_DISK0/
作为路径,但实际路径可能有所不同。