【问题标题】:Java/Android: Byte to file not saving?Java/Android:字节到文件不保存?
【发布时间】:2015-06-30 22:27:25
【问题描述】:

我想知道这段代码有什么问题:

public class MainActivity extends ActionBarActivity {
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textview);
        start();
    }
 public void start(){
        File file = new File("file.file");   
        try{

            FileOutputStream fos;
            fos = openFileOutput("file.file", Context.MODE_PRIVATE);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            if(file.length() == 0){
                BigInteger bi = new BigInteger("1000");
                bos.write(bi.toByteArray());
                bos.flush();
                bos.close();
                textView.setText(""+file.length()); //This is always 0, why? 
            }
            else{
             //do stuff, but since file.length() is always 0, this never happens. 
            }


}

所以基本上我想检查文件是否为空,如果为空,则向其中添加内容。所以我期望的是,当我下次打开应用程序时,长度不应该是空的,因为我之前已经写过了。但是,文件的长度总是0,这是为什么呢? File.length() 表示它返回字节数。

【问题讨论】:

  • @AndyThomas:正确,删除了我的评论。
  • @optional - 检查您的变量 file 是否引用了与您在方法 openFileOutput() 中打开的文件相同的实际路径。 (更好的是,将变量file 传递给openFileOutput(),以消除问题。)
  • 我刚刚检查了这个,但不幸的是问题仍然存在。 :(

标签: java android file fileoutputstream


【解决方案1】:

您需要在打开文件之前检查是否为空。打开输出文件会创建一个新的零长度文件,除非您指定“追加”模式。

【讨论】:

    【解决方案2】:

    我在第一次探索 Android 开发时遇到了类似的问题。尝试像这样创建文件:

    File f = new File(context.getFilesDir(), "file.file");
    

    context 是您应用的当前 android.content.Context。

    编辑:

    File f = new File(this.getFilesDir(), "file.file");
    

    ...因为 ActionBarActivity 扩展了 Activity,它是一个上下文。我有一段时间没有为 Android 开发了,但显然是 ActionBarActivity is now deprecated。查看该帖子以获取更多信息。

    【讨论】:

    • 嗯,这个问题有一个有趣的解决方案。这实际上只是解决方案的第 1 部分。有 3 个步骤: 第 1 步)按照 EJP 的回答。第 2 步)实施 ePluribusFunk 的答案。步骤 3) 将 start() 移至活动的 onStart 方法。它在前面的 onCreate 方法中,这意味着我必须退出应用程序才能让 if/else 语句再次运行。只需按例如“Home”最小化应用程序,下次打开应用程序时不会触发onCreate()
    猜你喜欢
    • 2011-12-20
    • 1970-01-01
    • 2013-04-13
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    相关资源
    最近更新 更多