String error “constant string too long”

前端 未结 4 1038
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 06:29

There is a 100,000-character text that need to be displayed. If I put it into String object, I get an error \"constant string too long\". The same is with StringBuffer object.

相关标签:
4条回答
  • 2021-02-08 06:44

    Strings Longer than 64k are not allowed to be used directly in java, but you can use them indirectly.

    • Step 1) click on your string
    • Step 2) press Alt + Enter keys together
    • Step 3) Select Extract String resource
    • Step 4) Name the resource and hit enter key.

    That is it. It will generate a string for you in strings.xml If you already have string in your strings.xml you can use this code to retrieve it:

    String yourStr = getString(R.string.sampleBigString);
    
    0 讨论(0)
  • 2021-02-08 06:44

    Yes constant String has a limit in java.

    So what you can do is copy your String in a text file and put in root of Assets folder and read from file by the following method.

    public String ReadFromfile(String fileName, Context context) {
    StringBuilder returnString = new StringBuilder();
    InputStream fIn = null;
    InputStreamReader isr = null;
    BufferedReader input = null;
    try {
        fIn = context.getResources().getAssets()
                .open(fileName, Context.MODE_WORLD_READABLE);
        isr = new InputStreamReader(fIn);
        input = new BufferedReader(isr);
        String line = "";
        while ((line = input.readLine()) != null) {
            returnString.append(line);
        }
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (isr != null)
                isr.close();
            if (fIn != null)
                fIn.close();
            if (input != null)
                input.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    return returnString.toString();
    }
    
    0 讨论(0)
  • 2021-02-08 06:58

    I think the length of constant strings in java is limited to 64K -- however, you could construct a string at run time that is bigger than 64K.

    0 讨论(0)
  • 2021-02-08 06:58

    I had same problem and the solution was the very big string literal that was assigned to one constant, to split it to several smaller literals assigned to new constants and concatenate them.

    Example:

    Very big string that can not compile:

    private static String myTooBigText = "...";
    

    Split it to several constants and concatenate them that compiles:

    private static String mySmallText_1 = "...";
    private static String mySmallText_2 = "...";
    ...
    private static String mySmallText_n = "...";
    
    private static String myTooBigText = mySmallText_1 + mySmallText_2 + ... + mySmallText_n;
    
    0 讨论(0)
提交回复
热议问题