Копирование файла и сохранение с другим именем файла
Я пытаюсь скопировать файл в Android. У меня есть путь к файлу файла. Я хочу скопировать его в другую папку с другим именем файла. Я использую приведенный ниже код, но он не работает. Мой файл видеофайл. Я получаю ошибку
/storage/emulated/0/testcopy.mp4: open failed: EISDIR (Is a directory)
Ниже мой код
File source=new File(filepath);
File destination=new File(Environment.getExternalStorageDirectory()+ "/testcopy.mp4");
copyFile(source.getAbsolutePath(),destination.getAbsolutePath());
private void copyFile(String inputPath, 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 );
out = new FileOutputStream(outputPath);
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());
}
}
2 ответа
Вы создаете каталог с именем "/storage/emulated/0/testcopy.mp4" здесь
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}
попробуй этот код
//create output directory if it doesn't exist
File dir = (new File (outputPath)).getParentFile();
if (!dir.exists())
{
dir.mkdirs();
}
Их главная проблема в том, что вы пытаетесь написать файл, который является каталогом. Чтобы избежать этого исключения, сначала создайте каталог, а затем запишите файл:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
// creating a new folder if doesn't exist
boolean success = folder.exists() || folder.mkdirs();
File file = new File(folder, "filename.mp4");
try {
if (!file.exists() && success) file.createNewFile();
...
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
...
}catch (IOException e){
e.printStackTrace();
}