简体   繁体   中英

IO Exception in FileInputStream.read. Android

I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.

Second activity:

    String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
    FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
    fos.write(s.getBytes());
    fos.close();

first (main) activity:

    static String FILENAME = "message_file.zip";
    FileOutputStream fos;
    try {
        //piece of code to guarantee that file exists
        fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
        fos.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    try {
        fis = openFileInput(FILENAME);
        messageString = new StringBuffer("");
        while ((length = fis.read(buffer)) != -1) {
            String temp = new String(buffer, 0,length);
            messageString.append(temp);
            fis.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Toast t = Toast.makeText(this, messageString, 3000);
    t.show();

I'm getting IO Exception in logcat at line:

  while ((length = fis.read(buffer)) != -1)

but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files. I tried to name my file like

static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt", 

to try different extensions, but always i'm getting the same IO Exception.

Thanks for suggestions.

of course you will get an IO Exception your file doesn't exit and you request to open it You forget this peice of code

File myFile = new File("/sdcard/mysdfile.txt");

In your first activity you can use this code

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    EditText txtData;
    Button btnWriteSDFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // bind GUI elements with local controls
    txtData = (EditText) findViewById(R.id.txtData);
    txtData.setHint("Enter some lines of data here...");

    btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
    btnWriteSDFile.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getApplicationContext(),SecondActivity.class);
            startActivity(i);
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }// onClick
    });
}
}

in the second one you can use this:

public class SecondActivity extends Activity {

    private TextView txtData2;
     @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        txtData2 = (TextView) findViewById(R.id.textView2);
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow + "\n";
            }
            txtData2.setText(aBuffer);
            myReader.close();
            Toast.makeText(getBaseContext(),
                    "Done reading SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

}

The first latout uses a linearlayout that contain an edittext and a button

The second a linearLayout with only a textview

Try it works fine if you find problem let me know!!

Ah i forget you have to add in your manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I found reason. Problem was in fragment:

while ((length = fis.read(buffer)) != -1) {
        String temp = new String(buffer, 0,length);
        messageString.append(temp);
        fis.close();
    }

What's the catch?

fis.close();

should be after while. I didn't notice that yesterday...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM