简体   繁体   English

Android写入文件会导致随机字符

[英]Android-Writing to a file results in random characters

Argargarg. 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. 我得到输入,并在其上调用getBytes。 It logs to the file something along the lines of "null" and random numbers after that. 它将类似“ null”和随机数的行记录到文件中。 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. String.getBytes返回字节数组,当您尝试执行toString()时,实际上是在写指向字符串的指针。 You already have String change this line 您已经有String更改此行

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. 只是在黑暗中拍摄,但我注意到您在调用getBytes()时未指定字符编码。 Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output. 除非输出文件的字符编码与系统默认编码的字符编码相同,否则您很容易在输出中出现乱码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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