Android和ObjectOutputStream的资源文件 [英] Android and ObjectOutputStream to resource file

查看:193
本文介绍了Android和ObjectOutputStream的资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很新的Andr​​oid开发,我的第一个项目是一个简单的游戏至极有一个显示屏和一个逻辑部分。我想补充一个保存功能的游戏,但我无法与实现。

I'm really new to android development, and my first project was a simple game wich has a display and a logic part. I would like to add a save feature to the game, but i'm having trouble with the implemetation.

我想去做这样,用一个ObjectOutputStream(只是重要的部分是包括在内)

I would like to do it this way, with an ObjectOutputStream (just the important part is included)

String filename = "res/raw/testfile.txt";
try
{
    FileOutputStream fileout = new FileOutputStream(filename);
    ObjectOutputStream out = new ObjectOutputStream(fileout);
    out.writeObject(...logic objects...);
} 
catch (Exception ex)
{
    //show the error message
}

但我总是得到一个错误消息至极说,没有这样的文件...。即使我创建的原始目录下的TESTFILE.TXT,它说了同样的错误。

But i always get an error message wich says, that "no such file ...". Even if i create a "testfile.txt" in the raw directory, it says the same error.

请帮我,我究竟做错了什么?

Please help me, what am i doing wrong?

推荐答案

创建的文件名的文件对象,然后检查文件是否存在。如果没有,则创建文件。如果是这样,你可以覆盖或提示用户,如果他们想覆盖它。然后将文件对象传递给你的FileOutputStream而不是文件名。事情是这样的:

Create a File object with the file name, then check to see if the file exists. If it doesn't, then create the file. If it does, you can just overwrite or prompt the user if they wish to overwrite it. Then pass the File object to your FileOutputStream instead of the filename. Something like this:

String filename = "res/raw/testfile.txt";
try
{
    File file = new File(filename);
    if (!file.exists()) {
        if (!file.createNewFile()) {
           throw new IOException("Unable to create file");
        }
    // else { //prompt user to confirm overwrite }

    FileOutputStream fileout = new FileOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(fileout);
    out.writeObject(...logic objects...);
} 
catch (Exception ex)
{
    //show the error message
}

另外,还要确保您关闭outputstreams以prevent任何资源泄漏。

Also make sure you close your outputstreams to prevent any resource leaks.

享受!

这篇关于Android和ObjectOutputStream的资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆