Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a File is Blank in Android

Tags:

java

file

android

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!

like image 225
Michael Yaworski Avatar asked Dec 02 '22 22:12

Michael Yaworski


1 Answers

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.

like image 125
Joni Avatar answered Dec 31 '22 10:12

Joni