Show me kotlin code to load a file on a background thread.
- User
Show me kotlin code to load a file on a background thread.
- Assistant
Sure! Here's an example of Kotlin code that demonstrates how to load a file on a background thread using coroutines:
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File fun main() { val filePath = "path/to/file.txt" GlobalScope.launch(Dispatchers.IO) { val fileContent = loadFileContent(filePath) println(fileContent) } // Other main thread tasks... } suspend fun loadFileContent(filePath: String): String = withContext(Dispatchers.IO) { val file = File(filePath) if (file.exists()) { file.readText() } else { throw IllegalArgumentException("File not found!") } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.