Home > Net >  Create and write files, in kotlin
Create and write files, in kotlin

Time:03-31

I'm new to kotlin, so sorry for such stupid question. I wonder, how can I create new file, then write to a file in mainactivity.kt

I tried this File(TestName).writeText(BruhHelp) and it doesnt work.. or im stupd

CodePudding user response:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

This is a java code I got from this `Stackoverflow Question.

Copy-paste this code and it should convert it to the corresponding Kotlin code.

Ps: we all started from zero and even after years it still makes us feel stupid sometimes. So don't worry and welcome to the programmers' life.:). all the best

CodePudding user response:

You can do File("some_filename"), but when you actually try to use it (like with writeText) in Android, you'll get an error like this:

java.io.FileNotFoundException: some_filename: open failed: EROFS (Read-only file system)

That's because in Android you're limited in where you can write files to, and if you supply a name or path to File, it's not treated as inside some working directory you have access to.

Here's the docs on writing files to internal storage - it's worth reading the whole section (on the left) so you get a feel for how it all works, and the different options you have (like a cache folder for temp stuff). But this is probably what you wanted to do:

File(filesDir, testName).writeText("we did it")

filesDir (from context.filesDir) gets the path to your app's own storage folder, and by passing that to File you're defining testName inside that folder. So the full path ends up correct, and one that the system allows you to actually write to

(And in case you didn't know, creating a File object doesn't create any actual files - it just represents a hypothetical location for a file, and a way to get info about whether it actually exists or not, read from it if it does, write to/create it etc. Calling writeText will create it if necessary - and possible!)

  • Related