Force saved file to have an extension on Android
-
I'm creating an Android app that's supposed to save .txt files like this:
QString chosenFile = QFileDialog::getSaveFileName(this, "Save", "", "Text files (*.txt)"); if(!chosenFile.isEmpty()){ //If the user didn't press Cancel if(!chosenFile.contains(QRegularExpression("\\.txt$"))){ //If the chosen file name doesn't end with .txt chosenFile += ".txt"; } QFile file(chosenFile); if(!file.open(QIODevice::WriteOnly)){ qDebug() << "Something bad happened"; return; } //Write the file contents }
What this does is that it opens a save file dialog. If I enter a file name that ends with
.txt
, it saves the file without a problem, as expected.If I enter a file name that doesn't end with
.txt
, I would expect it to save the file and automatically add.txt
at the end of the file name. But instead it creates an empty file with the file name I entered (without.txt
) and printsSomething bad happened
in the console.Why does it do this and how do I fix it?
-
@Donald-Duck Why don't you use https://doc.qt.io/qt-5/qstring.html#endsWith instead of using a regular expression? Did you check whether your if condition is actually hit? I mean: is "chosenFile += ".txt";" executed?
-
@jsulm said in Force saved file to have an extension on Android:
Did you check whether your if condition is actually hit? I mean: is "chosenFile += ".txt";" executed?
Yes, I checked, and it was.
Why don't you use https://doc.qt.io/qt-5/qstring.html#endsWith instead of using a regular expression?
I just wasn't aware that it existed. Now that I am I can use it, but it doesn't solve the problem.
-
@Donald-Duck If you see "Something bad happened" then it means that open() failed. You should print out https://doc.qt.io/qt-5/qiodevice.html#errorString in this case to see why it failed. So, please add proper error handling to get more information...
-
I would run the code in debugger and see what really happens to the file name and everything else. Perhaps the problem is before that code and the stack is corrupted or similar.
-
Note that on Android you cannot access files directly by absolute path if this path wasn't provided by file picker due to security reasons. So if file picker returned
some/path/to/file
you can operate only with that path, andsome/path/to/file.txt
will be another path which isn't provided as 'trusted'.This is true only for 'public' folders, like
Downloads
. You have full access to application's sandbox, if it can solve your problem. -
@IntruderExcluder Thanks, that explains why I get the error. Is there a way to get around it, for example by having the file picker add the extension automatically?
-
Not sure if it possible with Qt. I think you should dig into Android docs and make sure if it possible by doing with Java, then you prabably need to write some Java code and connect it via JNI. This might help you.