Jens Ehrlich
Jens Ehrlich

Reputation: 873

GWT platform independent newline character

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 a GWT based frontend. GWT compiles all java classes that are used by GWT (e.g. all classes in the fronted) into javascript. However, GWT cannot compile System.lineSeparator() as there is no equivalent method in javascript.

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

and

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

also cause GWT compiler exceptions. However,

String LINE_SEPARATOR = "\r\n";

works, but is not platform independent.

How can I get a platform independent newline character that is compatible to GWT?

Upvotes: 4

Views: 1957

Answers (2)

Thomas Broyer
Thomas Broyer

Reputation: 64541

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

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

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

That would require a recent version of GWT (2.6 at least, maybe 2.7).

The alternative would be to use super-source 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 of GWT, System.getProperty will work (for some properties) so you could possibly make it work for line.separator.

OR, you could use \n everywhere and only when you really need to have \r\n then do a replace("\n", "\r\n").

(if you ask me, I'd just use \n everywhere, even on Windows)

Upvotes: 3

Lukas Glowania
Lukas Glowania

Reputation: 498

A simple solution would be:

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

A more advanced solution could use deferred binding.

Upvotes: 1

Related Questions