检查Android中的文件是否为空

时间:2013-07-26 13:50:22

标签: java android file

这是我的代码示例。代码很长,只是为了测试文件是否为空,然后如果不是,则写入它。无论哪种方式,行if (!(data.equals("")) && !(data.equals(null)))都不起作用,即使文件为空,它仍会通过警报。

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();
}

此外,如果有人有办法缩短此代码,我会很高兴!

3 个答案:

答案 0 :(得分:11)

如果文件为空(没有内容),则其长度为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个字符,与从文件中成功读取的字符数无关。

答案 1 :(得分: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 
}

答案 2 :(得分:1)

由于您使用的是返回openFileInput("test.txt")的{​​{1}},请尝试

FileInputStream

我没有Java NIO经验。