Android studio copy file

Copy file from the internal to the external storage in Android

My app (Android API 15) makes a picture and stores it in the internal memory’s folder. Now, I want to copy this file to another folder inside of the external storage, e.g. /sdcard/myapp . I tried the following approaches:

Approach #1:

Approach #2:

Approach #3:

None of these methods doesn’t solve my task. In checked a number of related topics, and the only suggestion I found is to verify the persistence of

in AndroidManifest.xml and it does persist.

The approach #1 finishes the execution, but no folder and files are copied.

In the approach #2, the app fails with the exception java.lang.NullPointerException at outChannel = new FileOutputStream(dst).getChannel(); , but the object dst is not a null.

In the approach #3, I decided to verify if the destination object exists and it creates a folder if needed, but when I check if I can write, the check returns false .

I tried a couple of additional approaches, which succeeded to create an empty folder, but no files are really copied.

Since this is my very first step towards Android, I feel I miss some small thing. Please, point me, how to copy a file from one folder to another folder in Android, including file moving from internal to external memory.

Источник

Полный список

— работаем с файлами

Работа с файлами в Android не сильно отличается от таковой в Java. В этом уроке рассмотрим, как записать/прочесть файл во внутреннюю память и на SD-карту.

Project name: P0751_Files
Build Target: Android 2.3.3
Application name: Files
Package name: ru.startandroid.develop.p0751files
Create Activity: MainActivity

Рисуем экран main.xml:

4 кнопки, смысл которых понятен по тексту на них.

В onclick обрабатываем нажатия 4-х кнопок и вызываем соответствующие методы.

writeFile – запись файла во внутреннюю память. Используется метод openFileOutput, который на вход берет имя файла и режим записи: MODE_PRIVATE – файл доступен только этому приложению, MODE_WORLD_READABLE – файл доступен для чтения всем, MODE_WORLD_WRITEABLE — файл доступен для записи всем, MODE_APPEND – файл будет дописан, а не начат заново.

readFile – чтение файла из внутренней памяти. Используем метод openFileInput, принимающий на вход имя файла. Здесь и в методе записи внутреннего файла вы можете задать только имя файла, а каталог для ваших файлов вам уже выделен.

writeFileSD – запись файла на SD. Используем метод getExternalStorageState для получения состояния SD-карты. Здесь можно посмотреть какие бывают состояния. Нам нужно MEDIA_MOUNTED – когда SD-карта вставлена и готова к работе. Далее мы получаем путь к SD-карте (метод getExternalStorageDirectory), добавляем свой каталог и имя файла, создаем каталог и пишем данные в файл.

readFileSD – чтение файла с SD. Все аналогично предыдущему методу, только файл не пишем, а читаем.

Осталось в манифест добавить разрешение на работу с файлами на SD — android.permission.WRITE_EXTERNAL_STORAGE.

Все сохраним и запустим. Видим экран с 4-мя кнопками:

Внутренняя память

Жмем кнопку Записать файл. Видим в логе:

Проверим. Идем в File Explorer (Window > Show View > Other > Android > File Explorer) и открываем там папку data/data/ru.startandroid.develop.p0751files/files и видим там наш файл file.

Возвращаемся в эмулятор. Жмем Прочесть файл и в логе видим:

Это тот текст, который мы записывали в файл.

Читайте также:  Флай сенсорный с андроидом

SD карта

Теперь жмем Записать файл на SD.

Файл записан на SD: /mnt/sdcard/MyFiles/fileSD

Проверяем. Идем в FileExplorer и открываем там папку mnt/sdcard/MyFiles/ а в ней файл fileSD.

Возвращаемся в эмулятор и жмем кнопку Прочесть файл с SD. В логе видим:

Содержимое файла на SD

Этот текст мы и записывали.

mnt/sdcard — обычно этот путь ведет к содержимому SD-карты. Возможно у вас он будет другой.

В общем, при работе с файлами на SD вы используете стандартные java механизмы. А при работе с внутренним хранилищем для удобства можно использовать методы-оболочки от Activity:

openFileOutput – открыть файл на запись

openFileInput – открыть файл на чтение

И есть метод getFilesDir – возвращает объект File, соответствующий каталогу для файлов вашей программы. Используйте его, чтобы работать напрямую, без методов-оболочек.

Подробности работы в java с файловой системой я здесь описывать не буду. На нашем форуме пользователь SKR сделал отличную памятку по работе с файлами. Скорее всего, вы найдете там все что нужно.

Если у вас проверка SD-карты показывает, что карта недоступна (см. лог), то убедитесь в свойствах AVD, что у вас для SDCard указан Size или File. Если указаны, то попробуйте перезапустить AVD.

На следующем уроке:

— создаем экран с вкладками
— используем иконку в названии вкладки
— используем обработчик перехода между вкладками

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Implementing a File Picker in Android and copying the selected file to another location

I’m trying to implement a File Picker in my Android project. What I’ve been able to do so far is :

And then in my onActivityResult()

This is opening a file picker, but its not what I want. For example, I want to select a file (.txt), and then get that File and then use it. With this code I thought I would get the full path but it doesn’t happen; for example I get: /document/5318/ . But with this path I can’t get the file. I’ve created a method called PathToFile() that returns a File :

What I’m trying to do is let the user choose a File from anywhere means DropBox , Drive , SDCard , Mega , etc. And I don’t find the way to do it correctly, I tried to get the Path then get a File by this Path . but it doesn’t work, so I think it’s better to get the File itself, and then with this File programmatically I Copy this or Delete .

EDIT (Current code)

There I’ve got a question because I don’t know what is supported as text/plain , but I’m gonna investigate about it, but it doesn’t matter at the moment.

On my onActivityResult() I’ve used the same as @Lukas Knuth answer, but I don’t know if with it I can Copy this File to another part from my SDcard I’m waitting for his answer.

getPath() from @Y.S.

Is getting a NullPointerException :

EDIT with code working thanks to @Y.S., @Lukas Knuth, and @CommonsWare.

This is the Intent where I only accept files text/plain .

On my onActivityResult() I create an URI where I get the data of the Intent , I create a File where I save the absolute path doing content_describer.getPath(); , and then I keep the name of the path to use it in a TextView with content_describer.getLastPathSegment(); (that was awesome @Y.S. didn’t know about that function), and I create a second File which I called destination and I send the AbsolutePath to can create this File .

Читайте также:  Android icon all size

Also I’ve created a function that you have to send the source file , and destination file that we have created previously to copy this to the new folder.

Also I’ve created a function that says to me if this folder exist or not (I have to send the destination file , if it doesn’t exist I create this folder and if it does not I do not do nothing.

Thanks again for your help, hope you enjoy this code made with everyone of you guys 🙂

7 Answers 7

STEP 1 — Use an Implicit Intent :

To choose a file from the device, you should use an implicit Intent

STEP 2 — Get the absolute file path:

To get the file path from a Uri , first, try using

where data is the Intent returned in onActivityResult() .

If that doesn’t work, use the following method:

At least one of these two methods should get you the correct, full path.

STEP 3 — Copy the file:

What you want, I believe, is to copy a file from one location to another.

To do this, it is necessary to have the absolute file path of both the source and destination locations.

First, get the absolute file path using either my getPath() method or uri.getPath() :

Then, create two File objects as follows:

where CustomFolder is the directory on your external drive where you want to copy the file.

Then use the following method to copy a file from one place to another:

Try this. This should work.

Note: Vis-a-vis Lukas’ answer — what he has done is use a method called openInputStream() that returns the content of a Uri , whether that Uri represents a file or a URL.

Another promising approach — the FileProvider :

There is one more way through which it is possible to get a file from another app. If an app shares its files through the FileProvider , then it is possible to get hold of a FileDescriptor object which holds specific information about this file.

To do this, use the following Intent :

and in your onActivityResult() :

where mInputPFD is a ParcelFileDescriptor .

References:

As @CommonsWare already noted, Android returns you a Uri , which is a more abstract concept than a file-path.

It can describe a simple file-path too, but it can also describe a resource that is accessed through an application (like content://media/external/audio/media/710 ).

If you want your user to pick any file from the phone to read it from your application, you can do so by asking for the file (as you did correctly) and then use the ContentResolver to get an InputStream for the Uri that is returned by the picker.

Here is an example:

Important: Some providers (like Dropbox) store/cache their data on the external storage. You’ll need to have the android.permission.READ_EXTERNAL_STORAGE -permission declared in your manifest, otherwise you’ll get FileNotFoundException , even though the file is there.

Update: Yes, you can copy the file by reading it from one stream and writing it to another:

Deleting the file is probably not possible, since the file doesn’t belong to you, it belongs to the application that shared it with yours. Therefor, the owning application is responsible for deleting the file.

Источник

How to push files to an emulator instance using Android Studio

How am I able to push .txt files to the emulator using Android Studio?

Читайте также:  Настройки google android нет

9 Answers 9

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that «Enable Clipboard Sharing» is enabled. (under . ->Settings)

Update (May 2020): Android studio have new tool called Device File Explorer. You can access it in two way:

  1. By clicking on Device File Explorer icon in right bottom corner of android studio window.
  2. If you could not find its icon, inside Android Studio press shift button twice. Quick search window will appear, then type Device File in it and Device File Explorer will appear in search result and you can click it.

Then you can navigate to folder which you want to push your file in it. Right click on that folder and select upload(or press Ctrl + Shift + O ). Select file you want to upload and it will upload file to desired location.

Push file using adb.exe :

In Android 6.0+, you should use same process but your android application cannot access files which pushed inside SDCARD using DDMS File Explorer. It is the same if you try commands like this:

If you face EACCES (Permission denied) exception when you try to read file inside your application, it means you have no access to files inside external storage, since it requires a dangerous permission.

For this situation, you need to request granting access manually using new permission system in Android 6.0 and upper version. For details you can have a look in android tutorial and this link.

Solution for old android studio version:

If you want to do it using graphical interface you can follow this inside android studio menus:

Tools —> Android —> Android Device Monitor

Afterward, Android Device Monitor(DDMS) window will open and you can upload files using File Explorer. You can select an address like /mnt/sdcard and then push your file into sdcard.

Источник

Create/Copy File in Android Q using MediaStore

I am trying to find method which can handle create and copy of any file except Media files (Picture/Video/Audio) to copy from one place to other in internal storage in Android Q. In this I have my file created in my app folder and I want those to move to Download Folder or some directory which I can create in Internal storage and then move their.

I searched and found modified below code but missing some thing to make it workable. Can some one help.

Is above complete code as I’m getting error ‘Unknown URL’. What is missing? Please help.

2 Answers 2

1. Create and Write File

2. Find and Read File

3. Find and Overwrite File

Hope this may help you.

As you mentioned Environment.getExternalStoragePublicDirectory is marked deprecated. So there is no regular way to get the path to Downloads directory to save your file there. Alternatively you can use ACTION_CREATE_DOCUMENT to show path picker and then use returned uri to write file to selected location.

This is how to show picker:

And this is how to get selected uri and write file:

More information can be found here.

EDIT:

To pick a directory to persist files ACTION_OPEN_DOCUMENT_TREE can be used. Then use takePersistableUriPermission method to take granted persistable permission to be able to use it after device restart. And then use DocumentFile to execute file operations.

Open directory request:

Receive picked directory and take persistable permission:

And at last persist the file:

Review this repo for an example of ACTION_CREATE_DOCUMENT usage.

Источник

Оцените статью