简体   繁体   中英

Android-Writing to a file results in random characters

Argargarg.

I am trying to get information from a user input, then to write it to a system file. I get the input, and I call getBytes on it. It logs to the file something along the lines of "null" and random numbers after that. I tried getting it to a string, no luck there, it was a random chain of symbols Here is the specific code:

        TextView note_input=(TextView) findViewById(R.id.note_input);
    FileOutputStream fos=null;
    String newNote=note_input.getText().toString();
    Log.w("Debug",newNote);
    try {
        fos=openFileOutput("currentNote",Context.MODE_APPEND);
    } catch (FileNotFoundException e) {
        //IT_SHOUD_NOT_EXIST
    }
    try {
        Log.w("Debug",newNote.getBytes().toString());
        fos.write(newNote.getBytes());
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I appreciate any help!

String.getBytes returns array of bytes, and when you try to do toString() you are actually writing it's pointer to string. You already have String change this line

Log.w("Debug",newNote.getBytes().toString());

into

Log.w("Debug",newNote);

and you will have proper Log output, and File should be written properly already.

Hope this helps and enjoy your work

Just a shot in the dark, but I notice you're calling getBytes() without specifying the character encoding. Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output.

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