gpt4 book ai didi

android - 如何以编程方式 move 、复制和删除 SD 上的文件和目录?

转载 作者:IT老高 更新时间:2023-10-28 13:09:37 26 4
gpt4 key购买 nike

我想以编程方式 move 、复制和删除 SD 卡上的文件和目录。我已经进行了 Google 搜索,但找不到任何有用的信息。

最佳答案

在 list 中设置正确的权限

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

下面是一个以编程方式 move 文件的函数

private void moveFile(String inputPath, String inputFile, String outputPath) {

InputStream in = null;
OutputStream out = null;
try {

//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}


in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);

byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;

// write the output file
out.flush();
out.close();
out = null;

// delete the original file
new File(inputPath + inputFile).delete();


}

catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}

}

删除文件使用

private void deleteFile(String inputPath, String inputFile) {
try {
// delete the original file
new File(inputPath + inputFile).delete();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}

复制

private void copyFile(String inputPath, String inputFile, String outputPath) {

InputStream in = null;
OutputStream out = null;
try {

//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}


in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);

byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;

// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;

} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}

}

关于android - 如何以编程方式 move 、复制和删除 SD 上的文件和目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com