Android通过按下按钮将文件移动到外部设备
我需要制作一个按钮,以便它将特定文件移动到外部驱动器。我已将清单设置为允许写入外部存储器,但我找不到写入特定文件以写入外部存储器的代码。如果在AndroidManifest.xml中写入/读取外部存储器,请确保您具有以下权限:Android通过按下按钮将文件移动到外部设备,android,external,Android,External,我需要制作一个按钮,以便它将特定文件移动到外部驱动器。我已将清单设置为允许写入外部存储器,但我找不到写入特定文件以写入外部存储器的代码。如果在AndroidManifest.xml中写入/读取外部存储器,请确保您具有以下权限: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.W
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
备选方案
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
使用
getExternalFilesDir()
或Context
上的相关方法,或Environment
上的getExternalStoragePublicDirectory()
获取指向外部存储根位置的文件
对象。从这里开始,它就是标准的Java文件I/O(基于该根创建一个文件对象到特定位置,打开一个文件输入流和一个文件输出流,复制字节,等等)。。。copyExt(“/storage/emulated/0/obb/”Orange.txt“可选/外部USB/obb”);如果文件位于“/storage/emulated/0/obb/Orange.txt”(我为您填写第二个参数,以便传递一个空字符串),那么copyExt(“/storage/emulated/0/obb/Orange.txt”,”);
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}