这是我的代码示例。代码非常长,只是为了测试文件是否为空,然后如果不是,则将其写入。无论如何,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();
}
此外,如果有人能够简化这段代码,我会非常感激!