Error constant string too long

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. StringBuffer stringBuf...

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.

StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Long text here........"); //<-- error

Is there a solution to this beside cutting the text into smaller texts?

asked Jun 11, 2011 at 21:28

sandalone's user avatar

sandalonesandalone

40.8k63 gold badges219 silver badges334 bronze badges

4

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.

answered Jun 11, 2011 at 21:37

Sai's user avatar

9

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);

answered Aug 19, 2017 at 7:24

ali asghar tofighian's user avatar

0

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();
}

answered Jul 3, 2017 at 16:07

Rahul Jain's user avatar

Rahul JainRahul Jain

2762 silver badges11 bronze badges

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;

answered Nov 6, 2019 at 8:59

jascadev's user avatar

jascadevjascadev

191 gold badge1 silver badge5 bronze badges

Автор оригинала: baeldung.

1. Обзор

Когда мы пытаемся использовать переменную, которая слишком длинная для компилятора Java (больше 64 КБ), мы получаем ошибка “постоянная строка слишком длинная” от компилятора.

В этом учебнике мы покажем, как решить эту ошибку.

2. Описание проблемы

Давайте воспроизвести проблему, написав небольшой тест, где мы объявили Струнные это слишком долго:

@Test
public void whenDeclaringTooLongString_thenCompilationError() {
    String stringTooLong = "stringstringstring ... 100,000 characters ... string";  
    assertThat(stringTooLong).isNotEmpty();
}

Струнные содержащиеся в нашем строкаТоЛонг переменная содержит текст с более чем 100 000 символов. Строка с этими характеристиками доступна в файле, доступном по ссылке GitHub в конце. Чтобы получить поднятую ошибку, скопировать ее содержимое и заменить строкаТоЛонг ‘S значение.

Примечание, если мы забудем этот тест от некоторых IDEs, мы не получим никаких ошибок .

Причина в том, что IDEs, как правило, более мягким. Однако при попытке компиляции проекта (пакет mvn ) или просто при попытке выполнить тесты ( mvn test ) из командной строки мы получим следующий выход:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.058 s
[INFO] Finished at: 2020-03-14T17:56:34+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile (default-testCompile) on project core-java-strings: Compilation failure
[ERROR] :[10,32] constant string too long

Это связано с тем, что длина постоянной строки в файле класса ограничена 2-16 байтами в кодировании UTF-8.

3. Решение проблемы

Как только проблема будет воспроизведена, давайте найдем способ ее решения. Лучший способ – это хранить нашу строку в отдельном файле вместо того, чтобы в объявленной переменной или постоянной.

Давайте создадим текстовый файл для хранения содержимого нашей переменной и изменим наш тест, чтобы получить значение из файла:

@Test
public void whenStoringInFileTooLongString_thenNoCompilationError() throws IOException {
    FileInputStream fis = new FileInputStream("src/test/resources/stringtoolong.txt");
    String stringTooLong = IOUtils.toString(fis, "UTF-8");
    assertThat(stringTooLong).isNotEmpty();
}

Другим способом решения этой проблемы является хранение содержимого нашей переменной в файле свойств, а затем доступ к ней из нашего метода тестирования:

@Test
public void whenStoringInPropertiesString_thenNoCompilationError() throws IOException {
    try (InputStream input = new FileInputStream("src/main/resources/config.properties")) {         
        Properties prop = new Properties();
        prop.load(input);
        String sValue = prop.getProperty("stringtoolong");
        assertThat(sValue).isNotEmpty();
    }  
}

Теперь, если мы попытаемся составить наш проект или выполнить тесты, все будет работать:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  6.433 s
[INFO] Finished at: 2020-03-14T18:23:54+01:00
[INFO] ------------------------------------------------------------------------

Конечно, мы могли бы также ввести конкатенацию с нашей строки, но такие не рекомендуется. Если у нас есть такая длинная строка, наши java-файлы, скорее всего, не лучший дом для него в любом случае.

4. Заключение

В этой статье мы рассмотрели ошибку компиляции “постоянная строка слишком долго”. Мы увидели, что мы можем обойти его, сохраняя значение строк в отдельных файлах или свойствах конфигурации.

Как всегда, вы можете найти код более на GitHub .

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

I have a few really long strings in one class for initializing user information. When I compile in Eclipse, I don’t get any errors or warnings, and the resulting .jar runs fine.

Recently, I decided to create an ant build file to use. Whenever I compile the same class with ant, I get the «constant string too long» compile error. I’ve tried a number of ways to set the java compiler executable in ant to make sure that I’m using the exact same version as in Eclipse.

I’d rather figure out how to get the same successful compile I get in Eclipse in Ant than try to rework the code to dynamically concatenate the strings.

9 Answers
9

Someone is trying to send you a message :-) In the time you’ve spend fiddling with compiler versions you could have loaded the data from a text file — which is probably where it belongs.

Check out:

I found I could use the apache commons lang StringUtils.join( Object ) method to solve this.

public static final String CONSTANT = org.apache.commons.lang.StringUtils.join( new String
"This string is long",
"really long...",
"really, really LONG!!!"
);

The length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding, this should not be dependent on the compiler used. Perhaps you are using a different character set in your ant file than in eclipse, so that some characters need more bytes than before. Please check the encoding attribute of your javac task.

encoding

javac

Another trick, if I’m determined to put a long string in the source, is to avoid the compiler detecting it as a constant expression.

String dummyVar = "";
String longString = dummyVar +
"This string is longn" +
"really long...n" +
"really, really LONG!!!";

This worked for a while, but if you keep going too far the next problem is a stack overflow in the compiler. This describes the same problem and, if you’re still determined, how to increase your stack — the problem seems to be the sheer size of the method now. Again this wasn’t a problem in Eclipse.

Did you try this? Never tried it myself, but here is the relevant section:

Using the ant javac adapter
The Eclipse compiler can be used inside an Ant script using the javac adapter. In order to use the Eclipse compiler, you simply need to define the build.compiler property in your script. Here is a small example.

<?xml version="1.0" encoding="UTF-8"?>
<project name="compile" default="main" basedir="../.">

<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>

<property name="root" value="$basedir/src"/>

<property name="destdir" value="d:/temp/bin" />

<target name="main">
<javac srcdir="$root" destdir="$destdir" debug="on" nowarn="on" extdirs="d:/extdirs" source="1.4">
<classpath>
<pathelement location="$basedir/../org.eclipse.jdt.core/bin"/>
</classpath>
</javac>
</target>
</project>

I would really consider making your classes standards compatible. I believe the official limit is 65535, and the fact that Eclipse is more lenient is something that could change on you at the most inconvenient of times, and either way constantly having to get the project compiled with Eclipse can really start to limit you in too many ways.

String theString2 = IOUtils.toString(new FileInputStream(new
File(rootDir + "/properties/filename.text")), "UTF-8");

Add your string to values/strings.xml than call getResources.getString(R.string.yourstring)

Nothing of above worked for me. I have created one text file with name test.txt and read this text file using below code

String content = new String(Files.readAllBytes(Paths.get("test.txt")));

You can try this,

public static final String CONSTANT = new StringBuilder("Your really long string").toString();

By clicking «Post Your Answer», you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 707 что значит
  • Error committing is not possible because you have unmerged files
  • Error 707 sans
  • Error commit is not possible because you have unmerged files
  • Error 704 pubg

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии