2014-12-07 114 views
2

我想为Android编写我的第一个应用程序。我以前就认识Java,但自从使用Java之后已有一两年时间。你可以在Android中创建一个.dat文件吗

我想创建一个简单的文件在内部存储 - 我知道我不必设置任何权限来创建这样的文件?

  • 这是一个.dat文件我需要如果我想保存一个ArrayList? Android在创建时是否要求我使用文件扩展名?

即使只是尝试基本的文件创建 - 检查文件的存在,然后创建它,如果它不存在 - 不起作用。谁能告诉我我做错了什么? (我已经注释了读取ArrayList的尝试,因为我甚至不能创建该文件,只是尝试基本的文件创建。) (另外,我已经尝试了与“Shares.dat”代码而不是“股份”作为文件名,也没有工作,我甚至不知道Android是否能识别.dat文件,说实话我不是100%确定这是我需要的文件。)

(如果通过任何人都可以帮忙的机会,我可能无法测试任何解决方案,直到下周末......)

至于最后一行,原本它读'context.getFileDir()',但我的类扩展ActionBarActivity和我在互联网上发现了suggesti开始更改为this.getFileDir()。我得到一个空指针的警告,当我用context.getFileDir()

file = new File("Shares"); 

if (file.exists()){ 
    url.setText("File Exists"); 
    /*try{ 
    is = openFileInput("Shares"); 
    oi = new ObjectInputStream(is); 
    details = (ArrayList<Action>)oi.readObject();//warning 
    oi.close();//need finally?? 
    } 
    catch(Exception e){url.setText((e.getMessage()));} 
    url.setText(details.get(0).getAddresse());*/ 
} 
else 
{ 
try 
{ 
      **file = new File(this.getFilesDir(), "Shares");** 

} 
catch(Exception e){url.setText((e.getMessage()));} 
} 

回答

0

如果你想这是一个在私人存储中创建的文件的引用,你想使用getFileStreamPath("shares.dat"),而不是创建一个新的File对象。文件扩展名应该没有问题,但最好添加一个文件扩展名来跟踪这些文件的用途。

例如:

private boolean fileExists(Context _context, String _filename) { 
    File temp = _context.getFileStreamPath(_filename); 
    if(temp == null || !temp.exists()) { 
     return false; 
    } 
    return true; 
} 

然后,如果你想写一个名为“shares.dat”文件,那么你会用openFileOutput("shares.dat", Context.MODE_PRIVATE)。如果您想从该文件读入,则可以使用openFileInput("shares.dat")

// Read in from file 
if(fileExists(this, "shares.dat")) { 
    FileInputStream fis = this.openFileInput("shares.dat"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 
    ArrayList<Action> actions = (ArrayList<Action>)ois.readObject(); 
    ois.close(); 
} 

// Write out to file 
FileOutputStream fos = this.openFileOutput("shares.dat", Context.MODE_PRIVATE); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(actions); 
oos.close(); 

上面显示所有的流操作要抛出IOException,所以一定要根据需要来包装代码在try/catch块的能力。

+0

非常感谢您的回答mceley。我修改了我的代码: – Tunny 2014-12-07 20:33:55

+0

file = this.getFileStreamPath(“Shares.dat”); (file.exists()){ \t url.setText(“File Exists”); } else { \t url.setText(“File does not exist”); } – Tunny 2014-12-07 20:38:29

+0

对不起,我是新来张贴在这里,或缺乏这样做的经验。上面应该是代码。我收到消息'文件不存在'。第一行代码应该自己创建文件吗? – Tunny 2014-12-07 20:40:45

相关问题