https://kotlinlang.org logo
#squarelibraries
Title
# squarelibraries
c

Colton Idle

01/30/2023, 1:00 AM
Well apparently i suck at okio. whats the proper way to create a directory + file?
Copy code
@Throws(IOException::class)
fun writeStringToFile(path: Path, myMessage: String) {
  FileSystem.SYSTEM.createDirectories(path)

  FileSystem.SYSTEM.write(path) {
      writeUtf8(myMessage)
  }
}
Calling code
Copy code
writeStringToFile("mydir/myMessage.json".toPath(), "hello, moto")
Keep getting
java.io.IOException: failed to create directory: mydir
edit: maybe cuz im on an emu 🤔
e

eygraber

01/30/2023, 1:06 AM
Android?
c

Colton Idle

01/30/2023, 1:08 AM
Yeah
I don't work with files directly much so im probably missing something basic here. but i thought id be able to write files in my apps sandbox without issue
e

eygraber

01/30/2023, 1:10 AM
Is
mydir
just a placeholder? You should be using something like https://developer.android.com/reference/android/content/Context#getFilesDir() to get a directory that you can write to
c

Colton Idle

01/30/2023, 1:16 AM
oh. I thought FileSystem.SYSTEM would point to getFileDir
Copy code
writeStringToFile("${context.filesDir}/mydir/myfile.json".toPath(), "hello, moto")
going to give that a shot 🤞
Had to do this apparently
Copy code
@Throws(IOException::class)
fun writeStringToFile(pathWithFileName: Path, myMessage: String) {
  FileSystem.SYSTEM.createDirectories(pathWithFileName.parent!!)

  FileSystem.SYSTEM.write(pathWithFileName) {
      writeUtf8(myMessage)
  }
}
e

eygraber

01/30/2023, 1:39 AM
🙈 I always forget about that. I usually declare my files like:
Copy code
val someFile = File(parent, "foo/bar/baz").apply { parent.mkdirs() }
Aside from that, did you still have to use
context.filesDir
?
j

jw

01/30/2023, 2:23 AM
There's not much reason to use Okio here
b

Benoit Quenaudon

01/30/2023, 7:46 AM
other sidenote: injecting the filesystem will allow you to write tests sweet and easy
j

jw

01/30/2023, 7:00 PM
not if you bottom out in AtomicFile which only works on `File`s
c

Colton Idle

01/30/2023, 7:01 PM
Oh hm. So instead of okio + moshi + atomicFile I'll just use moshi + atomicFile
I've got okio + moshi working now which is nice though to save to disk. I tried getting atomicFile involved but couldn't figure out how to use it, but sounds like Jake says that's not possible
j

jw

01/30/2023, 7:02 PM
i still think you should try datastore again
86 Views