Independent new line symbol GWT

In one of my Java classes, I want to write a result that looks something like this:

String LINE_SEPARATOR = System.lineSeparator();
Stringbuilder result = new Stringbuilder();
result.append("some characters");
result.append(LINE_SEPARATOR);

      

The class using this code is passed to the GWT-based interface. GWT compiles all java classes that are used by GWT (like all classes on the front) to javascript. However, GWT cannot compile System.lineSeparator () since there is no equivalent method in javascript.

String LINE_SEPARATOR = System.getProperty(line.separator);

      

and

String LINE_SEPARATOR = String.format("%n");

      

also raise GWT compiler exceptions. However

String LINE_SEPARATOR = "\r\n";

      

works but is not platform independent.

How can I get platform independent newline character compatible with GWT?

+3


source to share


2 answers


Simplest thing that could work (out of my head):

String LINE_SEPARATOR = GWT.isClient() ? "\n" : getLineSeparator();

@GwtIncompatible
private static String getLineSeparator() {
  return System.lineSeparator();
}

      

This will require the latest version of GWT (minimum 2.6, maybe 2.7).

An alternative would be to use superuser with a simple provider class:



public class LineSeparatorProvider {
  public final String LINE_SEPARATOR = System.lineSeparator();
}

// in super-source
public class LineSeparatorProvider {
  public final String LINE_SEPARATOR = "\n";
}

      

Note that in a future version GWT System.getProperty

will work (for some properties) so you can make it work for line.separator

.

... OR , you can use \n

everywhere and only when you really need to have \r\n

, then do replace("\n", "\r\n")

.

(if you ask me, I would just use it \n

everywhere, even on Windows)

+3


source


A simple solution:

String systemLineSeparator;
String platform = Window.Navigator.getPlatform();
if(platform.toLowerCase().contains("windows")) {
    systemLineSeparator = "\r\n";
}
else {
    systemLineSeparator = "\n";
}

      



A more advanced solution might use lazy binding.

0


source







All Articles