Last active
April 12, 2021 11:43
-
-
Save lunandd/1ec350d4d41a0ac26a618a22bef10f45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pavlos.efstathiou.genid | |
import android.os.Build | |
import androidx.annotation.RequiresApi | |
import java.io.BufferedReader | |
import java.io.File | |
import java.nio.file.Files | |
import java.nio.file.StandardOpenOption | |
import java.lang.IllegalArgumentException | |
data class User(val id: Int, val fileName: String, var file: File,) { | |
init { | |
if (this.id < 1000 || this.id < 99999) id else throw IllegalArgumentException("id can't be less than 1000 and more than 99999") | |
} | |
} | |
var user = User(genRand(1000..99999), "id.txt", File("placeholder")) | |
@RequiresApi(Build.VERSION_CODES.O) | |
fun main() { | |
user.file = File(user.fileName) | |
// Files.write(user.file.toPath(), user.id.toString().toByteArray(), StandardOpenOption.APPEND) | |
// Files.readAllBytes(user.file.toPath()) | |
if (user.file.length() >= 5) read() | |
else write() | |
} | |
fun genRand(range: IntRange) : Int { | |
return (range).random() | |
} | |
@RequiresApi(Build.VERSION_CODES.O) | |
fun write() { | |
val isFileCreated : Boolean = user.file.createNewFile() | |
// Thanks https://www.tutorialkart.com/kotlin/kotlin-create-file/ | |
if(isFileCreated) println("File created successfully.") | |
user.file = File(user.fileName) | |
Files.write(user.file.toPath(), user.id.toString().toByteArray(), StandardOpenOption.WRITE) // Deletes data and writes new data | |
read() | |
} | |
@RequiresApi(Build.VERSION_CODES.O) | |
fun read() { | |
user.file = File(user.fileName) | |
Files.readAllBytes(user.file.toPath()) | |
val bufferedReader: BufferedReader = user.file.bufferedReader() | |
val inputString = bufferedReader.use { it.readText() } | |
println("Id is $inputString") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment