This is my code sample. The code is pretty long just to test if a file is blank and then if it isn't, write onto it. Either way, the line if (!(data.equals("")) && !(data.equals(null)))
doesn't work and even when the file is blank, it still goes through the 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();
}
Also, if anyone has a way of shorting up this code, I would be greatful!
If a file is blank (has no contents) its length is 0. The length returns also 0 if it doesn't exist; if this is a necessary distinction you can check if the file exists with the exists
method.
File f = getFileStreamPath("test.txt");
if (f.length() == 0) {
// empty or doesn't exist
} else {
// exists and is not empty
}
The current approach fails to work because inputBuffer
is an array of 1024 chars, and a strings created from it will also have 1024 chars, independently of how many chars were successfully read from the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With