在Android中检查文件是否为空

4

这是我的代码示例。代码非常长,只是为了测试文件是否为空,然后如果不是,则将其写入。无论如何,if (!(data.equals("")) && !(data.equals(null))) 这一行代码不起作用,即使文件为空,它仍然会执行Alert。

FileInputStream fIn = null;String data = null;InputStreamReader isr = null;
try{
    char[] inputBuffer = new char[1024];
    fIn = openFileInput("test.txt");
    isr = new InputStreamReader(fIn);
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    isr.close();
    fIn.close();
}catch(IOException e){}

// this is the check for if the data inputted from the file is NOT blank
if (!(data.equals("")) && !(data.equals(null)))
{
    AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
    builder.setMessage("Clear your file?" + '\n' + "This cannot be undone.")
    .setCancelable(false)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            EditText we = (EditText)findViewById(R.id.txtWrite);
            FileOutputStream fOut = null;

            OutputStreamWriter osw = null;
            try{
                fOut = openFileOutput("test.txt", Context.MODE_PRIVATE);
                osw = new OutputStreamWriter(fOut);
                osw.write("");
                osw.close();
                fOut.close();
                we.setText("");
            }catch(Exception e){}
        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

此外,如果有人能够简化这段代码,我会非常感激!

看看这篇帖子:https://dev59.com/oGw05IYBdhLWcg3whCJn - Flo
@Flo 谢谢你提供的链接。看起来很不错,应该可以用,但是实际上并没有 :( - Michael Yaworski
3个回答

16
如果一个文件是空的(没有内容),它的长度为0。如果文件不存在,长度也会返回0;如果这是必要的区别,你可以使用exists方法检查文件是否存在。
File f = getFileStreamPath("test.txt");
if (f.length() == 0) {
    // empty or doesn't exist
} else {
    // exists and is not empty
}

当前的方法无法正常工作,因为inputBuffer是一个包含1024个字符的数组,从中创建的字符串也将有1024个字符,而不管成功从文件中读取了多少个字符。


你确定这个文件真的是空的吗?它的长度是多少? - Joni
啊,openFileOutput是一个Android API函数,我原以为它是你自己编写的。它会在一个特定的目录中创建文件,你可以从getFilesDir获取该目录,并且还有一个不同的API函数可用于获取带有完整路径的File对象。请检查更新。 - Joni
File f = new File(getFilesDir(), "test.txt"); 可以工作!而且 File f = getFileStreamPath("test.txt"); 也可以工作。 - Michael Yaworski

2
尝试这个,祝你好运!
File sdcard = Environment.getExternalStorageDirectory();
        File f = new File(sdcard, "/yourfile");

if(!f.exsist()){
f.createNewFile();
//Use outwriter here, outputstream search how to write into a tet file in java code 
}

1
我不是在尝试查看它是否存在,而是在尝试查看它是否为空。另外,如果你创建了文件 File f = new File(sdcard, "/yourfile");,那么它不是总是存在吗?因为你刚刚创建了它。 - Michael Yaworski

1

由于您正在使用返回FileInputStreamopenFileInput("test.txt"),请尝试

FileInputStream fIn = openFileInput("test.txt");
FileChannel channel = fIn.getChannel();

if(channel.size() == 0) {
  // This is empty
}
else {
  // Not empty
}

我没有Java NIO经验。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接