0

I've got this function:

public static String read(Context context) {
    FileInputStream fis;
    try {
        fis = context.openFileInput(INFO_FILE_NAME);
        int bufferSize = 2 * 1024 * 1024; // 2 MiB
        byte[] buffer = new byte[bufferSize];
        fis.read(buffer);
        return new String(buffer);
    } catch (Exception e) {
        Log.d(TAG, 
                "Exception while reading General Information File:"
                + e.getMessage());
        return null;
    }
}

The function returns null. This means that there was an exception. However, nothing is logged to LogCat.

I've tried to debug it with Eclipse. Everything goes ok until the "return new String(buffer);" line. When I try to execute it, the debuggers jumps directly to the "return null;" line, without going through the "Log.d". In addition, when I'm in the "return null;" line, I can't see in the debugger the variable "e". How can this happen?

user936580
  • 1,223
  • 1
  • 12
  • 19
  • 1
    Please use this link: http://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa – Sam-In-TechValens Dec 25 '12 at 11:42
  • if ricintech's answer doesn't work then there must be problem with the Byets that you are generating.... – Sam-In-TechValens Dec 25 '12 at 11:47
  • It looks as if there is a problem with the encoding: if I add the encoding, no Exception is generated. However: 1) while can't I log the exception and 2) which is the right encoding? If I transfer the file to my PC, Notepad++ opens it as UTF-8 without BOM and shows it OK. However, if I use new String(buffer, "UTF-8"), non-ASCII characters are not shown correctly. – user936580 Dec 25 '12 at 11:53
  • I finally discovered that the only problem was the lack of encoding in the "return new String(buffer);" line, as you pointed out. If you want to post your comment as an answer, I will accept it. Thank you for your help. – user936580 Dec 26 '12 at 06:46
  • I have posted my answer :) – Sam-In-TechValens Dec 26 '12 at 06:55

2 Answers2

1

The main point to think while converting from bytes to String is the Encoding used in the conversion.

You have coded correctly few things that ricintech have referred are useful but the main point is to follow the standards as we discussed above in comments.

Sam-In-TechValens
  • 2,501
  • 4
  • 34
  • 67
0

Use this:

byte[] buffer = new byte[4096];
receivedData=new String(buffer);
Ricky Khatri
  • 952
  • 2
  • 16
  • 42