我想要做的是測試如果文件「turma.dat」已經存在,如果存在我只是打開它,如果它不存在,我創建一個新的文件並保存。當我第一次創建該文件時啓動該應用程序,但每次我再次啓動該應用程序時,該文件都將以白色創建。試圖加載文件到主要活動的onCreate
MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
var turma : Turma
var file = File("turma.dat")
if(file.exists()) {
turma = this.abrirArquivo()
}else{
turma = Turma()
ArquivoUtils(turma, this.applicationContext)
}
方法abrirArquivo:
@Throws(IOException::class, ClassNotFoundException::class)
fun abrirArquivo(): Turma {
val fis = this.applicationContext.openFileInput("turma.dat")
val ois = ObjectInputStream(fis)
return ois.readObject() as Turma
}
類ArquivoUtils:(負責接收Turma對象添加到文件並保存)
class ArquivoUtils internal constructor(var turminha: Turma, var context : Context) {
internal val fos = this.context.openFileOutput("turma.dat", Context.MODE_PRIVATE)
internal val oos = ObjectOutputStream(fos)
init {
this.salvarArquivo()
this.closeFile()
}
@Throws(IOException::class)
private fun salvarArquivo() {
oos.writeObject(turminha)
this.closeFile()
}
@Throws(IOException::class)
fun closeFile() {
oos.close()
}
你是什麼意思的「創建在白色」? – Les
該文件爲空。 –
so'File.exists(「turma.dat」)'返回true?你有調試器通過代碼? – Les