Write file Android

Write file Android
0
#1

Hi!

I need to write std::string in file on Android device. How can I do it?

0 Likes

#2

Umm… Maybe something like this:

auto fs = FileUtils::getInstance();
std::string path = fs->getWritablePath() + "text.txt";
fs->writeStringToFile("Hello world", path);

Or you mention something more “android specific”?

2 Likes

#3

This is a good way to do it that doesn’t involve you needing to mess with file and file streams in the std

1 Like

#4

Thank you for answer.

This code work on linux.

auto fs = FileUtils::getInstance();
//std::string path = fs->getWritablePath() + “text.txt”; - It don’t work on Linux and Android.
std::string path = fs->fullPathForFilename( “parameters.txt” );
fs->writeStringToFile( str, path );

But it don’t work on Android device.

Why is it happen?

0 Likes

#5

I such read string from file

char data = reinterpret_cast<char>(FileUtils::getInstance()->getFileData( path, “r”, &sizet ) );**

How can I know path to file which use getFileData()? I need write file which read function getFileData().

0 Likes

#6

In Android,
“Resources/parameters.txt” is placed in assets/parameters.txt.
It is archived in apk (apk is zip archive).
Therefore, it can not write directly.
This is the specification of the Android platform, you can not go against it.

auto fileUtils = FileUtils::getInstance();
// writable path:
// in android => /data/data/package_name/files/
std::string path = fileUtils->getWritablePath() + "parameters.txt";
if(!fileUtils->isFileExist(path)) {
    // First time, copy to writable path
    auto data = fileUtils->getDataFromFile("parameters.txt");
    fileUtils->writeDataToFile(data, path);
}else {
    // After the second time

    // read
    std::string text = fileUtils->getStringFromFile(path);
    ...

    // write
    std::string newText = "....";
    fileUtils->writeStringToFile(newText, path);
}

There is only one important point.
On Android, Resources/ the following files are placed in a read-only place.
You can not write directly to that file, nor can you get its full path.

1 Like

#7

It’s work! Thank you!

0 Likes

#8

thanks for this code I am able to write now but it removes old data from file how to prevent that?

0 Likes