Read only file system android studio

Trying to create a file in Android: open failed: EROFS (Read-only file system)

results in a FileNotFoundException with the message being /2ozjfFQzwv: open failed: EROFS (Read-only file system) where «2ozjfFQzwv» is what I passed as the name of the file.

I have tried this with and without the WRITE_INTERNAL_STORAGE permission. How do I create this file for writing?

Alternatively, I just want to be able to give an image to a new activity, and it is too large to serialize it in an extra. Is there an easier way than writing it to a file then reading from it again? All the questions on here seem to be about writing to an SD card, which I don’t want to do because many people don’t have SD card slots.

8 Answers 8

I have tried this with and without the WRITE_INTERNAL_STORAGE permission.

There is no WRITE_INTERNAL_STORAGE permission in Android.

How do I create this file for writing?

You don’t, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.

Please use the version of the FileOutputStream constructor that takes a File object. Create that File object based off of some location that you can write to, such as:

  • getFilesDir() (called on your Activity or other Context )
  • getExternalFilesDir() (called on your Activity or other Context )

The latter will require WRITE_EXTERNAL_STORAGE as a permission.

Is there an easier way than writing it to a file then reading from it again?

You can temporarily put it in a static data member.

because many people don’t have SD card slots

«SD card slots» are irrelevant, by and large. 99% of Android device users will have external storage — the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.

Источник

Read only file system on Android

I recently rooted my Droid X and everything seems to be working perfectly. I made some changes to build.prop and when I do adb push build.prop /system/ I get the following error: failed to copy ‘c:\build.prop’ to ‘/system//build.prop’: Read-only file system .

How can I fix this?

24 Answers 24

Not all phones and versions of android have things mounted the same.
Limiting options when remounting would be best.

Simply remount as rw (Read/Write):

Once you are done making changes, remount to ro (read-only):

works for me and seems to be the simplest solution.

Got this off an Android forum where I asked the same question. Hope this helps somebody else.

On a terminal emulator on the phone:

Then on the cmd prompt, do the adb push

While I know the question is about the real device, in case someone got here with a similar issue in the emulator, with whatever tools are the latest as of Feb, 2017, the emulator needs to be launched from the command line with:

For anything to be writable to the /system . Without this flag no combination of remount or mount will allow one to write to /system .

After the emulator is launched with that flag, a single adb remount after adb root is sufficient to get permissions to push to /system .

Читайте также:  Как убрать рекламу google android

Here’s an example of the command line I use to run my emulator:

The value for the -avd flags comes from:

I think the safest way is remounting the /system as read-write, using:

and when done, remount it as read-only:

This works for me, and is the simplest solution.

On my Samsung galaxy mini S5570 (after got root on cellphone):

Fist, as root, I ran:

as a normal user:

Grant root permissions on touch screen

list all mount points that we have and we can see, in my case, that /dev/stl12 was mounted on /system as ro (ready only), so we just need do:

Try the following on the command prompt:

Here is what worked for me. I was running an emulated Android 7.1.1 (Nougat) device.

On a terminal, I hit the following command. One thing to be noticed is the -writable-system flag

All the changes that you do on the /system contents will survive a restart.

I checked with emulator and following worked.

  1. adb reboot
  2. adb root && adb remount && adb push

As mentioned above as well, execute second step in single shot.

Open terminal emulator on the phone: then

after that daemon is started

then the read only is converted into the read-Write.

I found this article from google, and thought I’d add the steps necessary on a Sony Xperia Z (4.2.2).

The Sony has a watchdog process which detects when you’ve changed ro to rw on / and /system (these are the only ones I was trying to modify) and possibly others.

The following was what I ran to perform the changes I was trying to achieve. I pasted these into a window, because removing the execute bit from /sbin/ric needs to be done quickly in order to stop it restarting itself. (I tried stop ric ; this doesn’t work — although it worked on a previous version of android on the phone).

I modified the hosts file here, so this is the place you make the changes you need to the filesystem. To leave things the way we found them, do this:

At which point ric should automatically restart. (It restarted for me automatically.)

Adding a little bit more to Jan Bergström’s answer: Because Android is a Linux based system, and the path in Linux contains forward slashes(../), while using push command, use «/» to define destination path in the Android device.

For Example, the command goes: adb push C:\Users\admin\Desktop\1.JPG sdcard/pictures/

Notice that here, back slashes are used to define source path of the file to be pushed from windows PC and forward slashes are used to define destination path because Android is a Linux based system. You don’t have to act as a root to use this command and also, it works perfectly fine on production devices.

Sometimes you get the error because the destination location in phone are not exist. For example, some android phone external storage location is /storage/emulated/legacy instead of /storage/emulated/0 .

Thanks, Sérgio, for «mount» command without parameters idea. I’d need to made adb push into /data/data/com.my.app/lib for some test issue, and get «Read-only filesystem» message.

ls command shows me:

root@android:/ # ls -l /data/data/com.my.app/
drwxrwx—x u0_a98 u0_a98 2016-05-06 09:16 cache drwxrwx—x u0_a98 u0_a98 2016-05-06 09:04 files lrwxrwxrwx system system 2016-05-06 11:43 lib -> /mnt/asec/com.my.app-1/lib

So, it’s understood, that «lib» directory is separated from other application directories.

Command mount -o rw,remount /mnt/asec didn’t resolve «r/o fs» issue, it wants device parameter before directory parameter.

«df» command didn’t help also, but shows that my /mnt/asec/com.my.app-1 directory is at the separate mount point.

Then I looks by mount and voila!

root@android:/ # mount . /dev/block/dm-4 /mnt/asec/com.my.app-1 ext4 ro,dirsync,relatime 0 0

Next steps are already described upwards: remount to RW, push and remount back to RO.

it sames that must extract and repack initrc.img and edit init file with the code of mount /system

Copy files to the SD-card?

Well, I assume you like to copy data to the Sd-card from the developers computer? You might have rooted the devise and made the area you address available?) I had about the same problem to upload data files for my application(Android Studio 1.3.2 in Win7), but.

  • First the adb command-shell has to be found in th path: PATH=%PATH%;C:\Users\XXXXX\AppData\Local\Android\sdk\platform-tools (the folder AppData is hidden, so you have to set the folder setup not hiding concealed files and folder to find it, Path works regardless)
  • You have to spell the folder path right or you get a read-only error message, most likely it must start with /sdcard or it is read only area. As soon as I did no problem pushing the file to the emulator.

So for instance the the adb command can look like this:

Источник

Файловая система только для чтения на Android

Я недавно рутировал свой Droid X и все вроде отлично работает. Я сделал некоторые изменения, build.prop и когда adb push build.prop /system/ я получаю, я получаю следующую ошибку: failed to copy ‘c:\build.prop’ to ‘/system//build.prop’: Read-only file system .

Как я могу это исправить?

Не на всех телефонах и версиях Android установлены одинаковые вещи.
Ограничение параметров при перемонтировании было бы наилучшим.

Просто перемонтируйте как rw (чтение / запись):

После внесения изменений перемонтируйте в ro (только для чтения):

работает для меня и, кажется, самое простое решение.

Получил это на форуме Android, где я задавал тот же вопрос. Надеюсь, это поможет кому-то еще.

На эмуляторе терминала на телефоне:

Затем в командной строке cmd выполните adb push

Хотя я знаю, что вопрос касается реального устройства, в случае, если кто-то попал сюда с похожей проблемой в эмуляторе, с какими-либо инструментами, самыми последними по состоянию на февраль 2017 года, эмулятор должен быть запущен из командной строки с помощью:

Для чего-либо, чтобы быть доступным для записи /system . Без этого флага ни одна комбинация remount или mount не позволит писать /system .

После запуска эмулятора с этим флагом достаточно одного adb remount после, adb root чтобы получить разрешения для отправки /system .

Вот пример командной строки, которую я использую для запуска своего эмулятора:

Значение для -avd флагов происходит от:

Я думаю, что самый безопасный способ это перемонтировать / system как read-write, используя:

и когда закончите, перемонтируйте его только для чтения:

На моем Samsung galaxy mini S5570 (после получения рута на мобильном телефоне):

Кулак, как корень, я побежал:

как обычный пользователь:

Предоставление прав root на сенсорном экране

перечислите все точки монтирования, которые у нас есть, и мы можем видеть, в моем случае, что / dev / stl12 был смонтирован в / system как ro (только готово), поэтому нам просто нужно сделать:

Попробуйте следующее в командной строке:

Это работает для меня и является самым простым решением.

Вот что сработало для меня. У меня было эмулированное устройство Android 7.1.1 (Nougat).

На терминале я нажал следующую команду. Одна вещь, которую нужно отметить, это флаг -writable-system

На другой вкладке

Все изменения, внесенные вами в содержимое / system, сохранятся после перезапуска.

Я проверил с эмулятором и следующий работал.

  1. перезагрузка adb
  2. корень adb && adb remount && adb push

/ рабочий стол / hosts / system / etc / hosts

Как уже упоминалось выше, выполните второй шаг за один выстрел.

Откройте эмулятор терминала на телефоне: тогда

после запуска этого демона

затем только чтение преобразуется в чтение-запись.

работает для меня

Я нашел эту статью в Google и подумал, что добавлю шаги, необходимые для Sony Xperia Z (4.2.2).

У Sony есть сторожевой процесс, который обнаруживает, когда вы изменили ro на rw на / и / system (это единственные, которые я пытался изменить) и, возможно, другие.

Ниже было то, что я побежал, чтобы выполнить изменения, которые я пытался достичь. Я вставил их в окно, потому что удаление бита выполнения из / sbin / ric должно быть выполнено быстро, чтобы остановить его перезапуск. (Я пытался stop ric ; это не работает — хотя это работало на предыдущей версии Android на телефоне).

Я изменил файл hosts здесь, так что это место, где вы вносите необходимые изменения в файловую систему. Чтобы оставить вещи такими, какими мы их нашли, сделайте так:

В этот момент RIC должен автоматически перезапустить. (Он перезапустился для меня автоматически.)

Добавим немного больше к ответу Яна Бергстрёма: поскольку Android — это система на основе Linux, а путь в Linux содержит косую черту (../), при использовании команды push используйте «/» для определения пути назначения на устройстве Android.

Например, команда выглядит так: adb push C: \ Users \ admin \ Desktop \ 1.JPG sdcard / pictures /

Обратите внимание, что здесь, обратная косая черта используется для определения пути к исходному файлу, который должен быть передан с компьютера с Windows, а прямая косая черта используется для определения пути назначения, потому что Android — это система на основе Linux. Вам не нужно выступать в роли пользователя root, чтобы использовать эту команду, а также, она отлично работает на производственных устройствах.

Иногда вы получаете сообщение об ошибке, потому что адресата в телефоне не существует. Например, некоторые андроид телефон внешнего хранилища /storage/emulated/legacy вместо /storage/emulated/0 .

Спасибо, Сержио , за команду «mount» без идеи параметров. Мне нужно сделать adb push в /data/data/com.my.app/lib течение некоторого тестового вопроса, и получить «только для чтения файловой системы» сообщение.

Команда ls показывает мне:

root@android:/ # ls -l /data/data/com.my.app/
drwxrwx—x u0_a98 u0_a98 2016-05-06 09:16 cache drwxrwx—x u0_a98 u0_a98 2016-05-06 09:04 files lrwxrwxrwx system system 2016-05-06 11:43 lib -> /mnt/asec/com.my.app-1/lib

Итак, понятно, что каталог «lib» отделен от других каталогов приложений.

команда mount -o rw,remount /mnt/asec не решила проблему «r / o fs», она хочет, чтобы параметр устройства был указан перед параметром каталога.

Команда «df» тоже не помогла, но показывает, что мой /mnt/asec/com.my.app-1 каталог находится в отдельной точке монтирования.

Тогда я смотрю mount и вуаля!

root@android:/ # mount . /dev/block/dm-4 /mnt/asec/com.my.app-1 ext4 ro,dirsync,relatime 0 0

Следующие шаги уже описаны вверх: перемонтировать в RW, нажать и перемонтировать обратно в RO.

это то же самое, что нужно распаковать и перепаковать файл initrc.img и отредактировать init файл с кодом mount / system

Копировать файлы на SD-карту?

Ну, я полагаю, вам нравится копировать данные на SD-карту с компьютера разработчиков? Возможно, вы укоренили устройство и сделали доступной область, к которой обращаетесь?) У меня была примерно такая же проблема при загрузке файлов данных для моего приложения (Android Studio 1.3.2 в Win7), но.

  • Сначала нужно найти командную оболочку adb по следующему пути: PATH =% PATH%; C: \ Users \ XXXXX \ AppData \ Local \ Android \ sdk \ platform-tools (папка AppData скрыта, поэтому необходимо установить в настройках папки не скрываются скрытые файлы и папка для ее поиска, путь работает независимо)
  • Вы должны правильно указать путь к папке, или вы получите сообщение об ошибке только для чтения, скорее всего, оно должно начинаться с / sdcard или это область только для чтения. Как только я без проблем запихнул файл в эмулятор.

Так, например, команда adb может выглядеть так:

Источник

Читайте также:  Процессор android phone остановлено
Оцените статью