Search code examples
javajavac

why java.nio.charset.Charsets compile error?


import java.nio.charset.Charsets in my class UriCodec.java,but when i use javac(jdk6) compile this class error. for example: javac UriCodec.java

error code:

import java.nio.charset.Charsets;
                       ^
UriCodec.java:140: Can not find symbol
symbol: Variable Charsets
position: class com.android.exchange.utility.UriCodec
        appendEncoded(builder, s, Charsets.UTF_8, false);
                                  ^
UriCodec.java:144: Can not find symbol
symbol: Variable Charsets
position: class com.android.exchange.utility.UriCodec
        appendEncoded(builder, s, Charsets.UTF_8, true);
                                  ^
UriCodec.java:203: Can not find symbol
symbol: Variable Charsets
position: class com.android.exchange.utility.UriCodec
        return decode(s, false, Charsets.UTF_8);
                                ^
UriCodec.java:214: Can not find symbol
symbol: Method toHexString(byte,boolean)
position: class java.lang.Byte
        sb.append(Byte.toHexString(b, true));
                      ^
5 error

my class:

import java.nio.charset.Charset;
import java.nio.charset.Charsets;
public abstract class UriCodec {


    public final void appendEncoded(StringBuilder builder, String s) {
        appendEncoded(builder, s, Charsets.UTF_8, false);
    }

    public final void appendPartiallyEncoded(StringBuilder builder, String s) {
        appendEncoded(builder, s, Charsets.UTF_8, true);
    }

    public static String decode(String s) {
        return decode(s, false, Charsets.UTF_8);
    }


   public final String encode(String s, Charset charset) {
        // Guess a bit larger for encoded form
        StringBuilder builder = new StringBuilder(s.length() + 16);
        appendEncoded(builder, s, charset, false);
        return builder.toString();
    }
}

Solution

  • There's no such class as Charsets. There's Charset (singular) but that's not the same thing...

    I suspect you got a message like this:

    UriCodec.java:1: error: cannot find symbol
    import java.nio.charset.Charsets;
                           ^
      symbol:   class Charsets
      location: package java.nio.charset
    1 error
    

    When you get a compiler error, read it. If the compiler says it can't find a symbol, then there's usually a very good reason for it - so double-check that you've spelled everything correctly, with the correct casing.

    Change your import to

    import java.nio.charset.Charset;
    

    and all should be well.

    ... or if you meant a different Charsets class (such as the one in Guava) you should add an import for that class instead.