4

这是我的代码示例。代码很长,只是为了测试文件是否为空白,如果不是,则写入该文件。无论哪种方式,该行都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();
}

另外,如果有人有办法缩短这段代码,我会很感激的!

4

3 回答 3

14

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

于 2013-07-26T13:53:32.220 回答
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 
}
于 2013-07-26T13:59:11.483 回答
1

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

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

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

我没有 Java NIO 经验。

于 2013-07-26T13:55:42.320 回答