0

I want to read a string from a file which is in the asset folder. I can read wihtout problem but I have a strange problem when I try to manipulate these string.

Content of my data file
[001]
[SCA] 23
[NBT] 2
[END]

public static String readLevelFromFileAsset(String filename, Context ctx, String levelID) 
{
    String Content = null;
    try {
        AssetManager am = ctx.getAssets();
        InputStream is = am.open(filename);

        if ( is != null )
        {
            InputStreamReader inputStreamReader = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((receiveString = bufferedReader.readLine()) != null ) 
            {
                Log.d(TAG, receiveString + " : " + receiveString.length());

                byte[] bytes = EncodingUtils.getAsciiBytes(receiveString);
                for(int i = 0; i < bytes.length; i++)
                {
                    Log.d(TAG,String.valueOf(bytes[i]));
                }

                if(receiveString == "[001]")
                {
                    Log.d(TAG, "Hello");
                    stringBuilder.append(receiveString);
                }
            }

            is.close();
            Content = stringBuilder.toString();
        }

    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally
    {
        Log.d(TAG, Content);
    }


    return Content;
}

Ce content of the logs:
[001] : 5
91
48
48
49
93

My question is : WHY the word 'Hello' is not written in the log ? it seems that in the 'IF' the receivestring is unknown !

gigi38660
  • 1
  • 1

2 Answers2

3

You should not compare strings using ==, you should use equals() or equalsIgnoreCase(), change:

if(receiveString == "[001]")

to

if(receiveString.equals("[001]"))
marcinj
  • 48,511
  • 9
  • 79
  • 100
2

You're comparing objects via the == operator. This is only returning true if you're accessing the exact same object. Use equals() to compare objects in order to check whether they are equal.

if(receiveString.equals("[001]"))

should solve it for you.

if("[001]".equals(receiveString))

would even be null safe.

Ben Weiss
  • 17,182
  • 6
  • 67
  • 87