2017-09-23 36 views
0

我想要做的是測試如果文件「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() 
} 
+0

你是什麼意思的「創建在白色」? – Les

+0

該文件爲空。 –

+0

so'File.exists(「turma.dat」)'返回true?你有調試器通過代碼? – Les

回答

0

file.exists()是probalby不看你期望的地方。方法openFileInputopenFileOutput處理應用程序私有位置中的文件。當你聲明文件,你說......

var file = File("turma.dat") 

而是使用類似...

var file = File(this.filesDir, "turma.dat") 

看看是否有幫助。閱讀Saving Files得到的如何使用文件Androidl

工作順便說一句,使用調試器和單步調試和驗證file.exists回報你的期望更好地把握。 (如果你不知道如何使用調試器,那麼從學習如何開始)。

+0

我試圖應用您所說的更改,現在嘗試打開應用程序時會崩潰。 –

+0

這可能是進步。什麼是例外?你可以將你的代碼包裝在try/catch塊中並打印異常。 – Les

+0

致命例外:main 進程:com.example.thial.estudandokotlin,PID:10306 java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.thial.estudandokotlin/com.example.thial.estudandokotlin.MainActivity} :java.io.EOFException –