Reputation: 383
The screenshot of my intelliJ IDE as I could not post a picture directly (by the way am using jdk 10) For some reason I need to output a String based on input and there might be new lines in the String. To make the program working on different platform I use a variable to store System.lineSeparator() and insert it when needed. But then I realized that intelliJ shows that it is deprecated. So my question is, why is this function deprecated? Is it a bad practice using line separators? What is the better way of doing this?
final String NEW_LINE = System.lineSeparator();
String output = "Line one" + NEW_LINE + "Line two";
WriteToFile(output);
update: the picture shows the warning in my intelliJ IDE. The problem might be caused by my configuration. According to answers below(thank you all for answering btw), maybe I should ask "Is it" before "why" next time.
Upvotes: 3
Views: 5679
Reputation: 1
You can use System.getProperty
with line.separator
if your java version does not allow System.lineSeparator()
.
final String LINE_SEPARATOR = System.getProperty("line.separator");
Upvotes: 0
Reputation: 26577
Probably the System.lineSeparator()
was configured to be annotated with @Deprecated
by mistake. You can position the text cursor on the method call and press Alt+Enter and invoke Deannotate @java.lang.Deprecated
to remove the annotation.
Upvotes: 1
Reputation: 1851
why is this function deprecated?
This is the choice implemented by either a plugin, an add-on or a configuration setting in your IntelliJ (as some comments pointed out, their IntelliJ does not strike it as deprecated). As far as I can see, the only choice for deprecating this would be that it may bring a compatibility error. However, from the Java System class documentation:
lineSeparator
public static String lineSeparator()
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
There is no indication about deprecation of the System.lineSeparator()
, as far as the version it was implemented (Java 7) and up until the last version available (Java 10). If it really burns your mind, you may want to ask the community directly.
Is it a bad practice using line separators?
Not at all (I may be wrong, as far as my knowledge goes), especially since you are using a line separator which is compatible with any system you are running your code on (theorically).
What is the better way of doing this?
I don't have any better advice about your choice on design regarding this piece of code. It seems that Michal Lonski has one, regarding that point.
Upvotes: 6
Reputation: 887
You can use String.format
and %n
:
String output = String.format("Line one%nLine two");
The %n
is a platform-independent newline character.
Upvotes: 0