Java, end of line with system.out.print - java

I have done some research concerning System.out.print() and System.out.println() and I discovered that System.out.println() add the end of line at the end of printed line.
System.out.println("Test");
Output only :
Test
but does not print end of the line.
System.out.print("Test");
Output only:
Test
but does not end the line and leave some place for other words or numbers, etc etc.
A more illustrative way is:
Test_____________________________________________ (All "blank" spots)
Is there a way to, force an end of line with System.out.print() directly after the word Test? Will the usage of % will remove the "blank" spots?
Or a way to code a function that will end the line after I used several System.out.print() to print a sentence?
For exemple :
System.out.print("Test);
System.out.print("Test);
will outpost a pure:
Test Test
like System.out.println("Test Test")

You can append line separator, Note that it is platform dependant, so :
Windows ("\r\n")
Unix/Linux/OSX ("\n")
pre-OSX Mac ("\r")
If you want to get line separator depending on actual system you can just use :
System.getProperty("line.separator"); for pre Java 7
System.lineSeparator(); for Java 7
Then you just append your separator to your string in System.out.print, like :
System.out.print("Word\n");

You can do System.out.print("Test\n").

System.out.println("Test"); will print end of the line. When you don't see it in your IDE it doesn't mean it isn't here. Try:
System.out.println("Test1");
System.out.println("Test2");
System.out.println("Test3");
which will produce:
Test1
Test2
Test3
From the docu of the println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println()
and from the docu of the println():
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

For getting an OS independent EOL character you could try
System.getProperty("line.separator");
and then appending that to your string ?
Why do you want to manually do that though since there is a function to do it for you ?

You can explicitly include a newline char in what you are printing:
System.out.print("Test\n");
This will force the newline while using the print function.

You can force a manual newline like so:
System.out.print("Test\n");
You can also mix the two when you need to print then end the line like so:
System.out.print("This is on ");
System.out.print("the same line.");
System.out.println(" and now we'll end the line");
System.out.println("This is on a different line.");

Related

How to obtain text from a String variable?

String s = System.lineSeparator();
System.out.println(s);
I try to obtain text from variable s, but why is there no text in variable s ?
Try following code on your system
for(byte b : System.lineSeparator().getBytes()){
System.out.println(b);
}
It will print either
10
OR
13
10
Here I print the ascii code for whatever I got from System.lineSeparator().
ascii code for \n is 10 and for \r is 13.
It is also given in documentation of System.lineSeparator()
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
So the point is you didn't see any output because if you try to print \r or \n because \r represents line feed and \n represents next line. And you cannot see them on console. But they will have their effects in strings.
The System.lineSeparator(); returns a string that the system uses to generally separate lines in, say for example, an input from the Standard Input.
This is generally a new line character and so when you print it in your program, you will not "See" it as is.
Try using this:
String s = System.lineSeparator();
System.out.println("~~" + s + "~~");
This will help you distinguish the output. You should see something like this:
~~
~~
This output would indicate the the new line character is separating the ~~ characters in your print statement.
Hope this helps!
System.lineSeperator() will mostly return "\r\n", so when you sysout it actualy prints a new line.

How to make a space between a line in Java?

System.out.print("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
I tried to use println(), thinking that it would create a blank line, but it didn't.
Try:
public class Main {
public static void main(String args[]) {
System.out.println("I have a question, can you assist me?\n");
System.out.println("How can I make a gap between these two statements?");
}
}
P.S. \n is newline separator and works ok at least on Windows machine. To achieve truly crossplatform separator, use one of methods below:
System.out.print("Hello" + System.lineSeparator()); // (for Java 1.7 and 1.8)
System.out.print("Hello" + System.getProperty("line.separator")); // (Java 1.6 and below)
Here's what's going on.
System.out.print("I have a question, can you assist me?");
You have now printed a bunch of characters, all on the same line. As you have used print and have not explicitly printed a newline character, the next character printed will also go onto this same line.
System.out.println();
This prints a newline character ('\n'), which is not the same as printing a blank line. Rather, it will cause the next character printed to go onto the line following the current one.
System.out.println("How can I make a gap between these two statements?");
Since you just printed a newline character, this text will go onto the line directly following your "I have a question" line. Also, since you have called println, if you print anything right after this, it will go onto a new line instead of the same one.
To put a blank line between the two statements, you can do this (I know, I know, not entirely cross-platform, but this is just a very simple example):
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
Since you are now printing two newline characters between the two lines, you'll achieve the gap that you wanted.
Beware that adding a bare "\n" to the string you are outputting is liable to make your code platform specific. For console output, this is probably OK, but if the file is read by another (platform native) application then you can get strange errors.
Here are some recommend approaches ... that should work on all platforms:
Just use println consistently:
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap?");
Note: println uses the platform default end-of-line sequence.
Use String.format:
String msg = "I have a question, can you assist me?%n%nHow can " +
"I make a gap?%n";
System.out.print(String.format(msg));
Note: %n means the platform default end-of-line sequence.
Note: there is a convenience printf method in the PrintWriter interface that does the same thing as String.format
Manually insert the appropriate end-of-line sequence into the string; see the end of #userlond's answer for examples.
Use:
system.out.println("\n");
\n takes you to new line.
You can use the below code. By that method you can use as much line gap as you want. Just increase or decrease the number of "\n".
System.out.print("Hello \n\n\n\n");
System.out.print("World");
If you want to leave a single line space in java,you could use
System.out.println("");
But if you want to leave Multiple line spaces in java,you could use
System.out.println("/n/n/n/n");
which means that each '/n' represents a single line
What about this one?
public class Main {
public static void main(String args[]) {
System.out.println("Something...");
System.out.printf("%n"); // Not "\n"
System.out.println("Something else...");
}
}
"%n" should be crossplatform-friendly.

JTextPane and newlines

I'm writing a program that (at one point) makes a command-line call to another native application, gets the output from that application, and puts it into a JTextPane as a String. The problem is, it doesn't seem to grab the newline characters the way it should. Because I'm using linux, each line ends with a ^M instead of a \n.
Is there any way to tell Java to look for those and create a newline in the string?
private void getSettings() {
Commander cmd = new Commander();
settings = cmd.getCommandOutput("hdhomerun_config " + ipAddress + " get /sys/boot");
settingsTextPane.setText(settings);
}
I end up with the output barfed into one line and wrapped around in the text pane.
As I recall Unix displays ^M for the carriage return character \r so you could try to replace it by using the replace method of the String class
settingsTextPane.setText(settings.replace('\r', '\n'));
Thanks guys, I looked through my code again and realized I was reading the output from the program one line at a time, and just appending the lines. I needed to add a \n at the end of each line that I read. Correct me if I'm wrong, but I believe Java automatically corrects newlines based on your operating system.

How to split string with empty new line

my file contains this string:
a
b
c
now I want to read it and split it with empty line so I have this:
text.split("\n\n"); where text is output of file
problem is that this doesnt work. When I convert new line to byte I see that "\n\n" is represented as 10 10 but new line in my file is represented by 10 13 10 13. So how I can split my file ?
Escape Description ASCII-Value
\n New Line Feed (LF) 10
\r Carriage Return (CR) 13
So you need to try string.split("\n\r") in your case.
Edit
If you want to split by empty line, try \n\r\n\r. Or you can use .readLine() to read your file, and skip all empty lines.
Are you sure it's 10 13 10 13? It always should be 13 10...
And, you should not depend on line.separator too much. Because if you are processing some files from *nix platform, it's \n, vice versa. And even on Windows, some editors use \n as the new line character. So I suggest you to use some high level methods or use string.replaceAll("\r\n", "\n") to normalize your input.
Keep in mind, sometimes you have to use:
System.getProperty("line.separator");
to get the line separator, if you want to make it platform independent. You can also use BufferedWriter's newLine() method, that takes care of that automatically.
Try using:
text.split("\n\r");
Why are you splitting on \n\n?
You should be splitting on \r\n because that's what the file lines are separated by.
Try to use regular expressions, something like:
text.split("\\W+");
text.split("\\s+");
LF: Line Feed, U+000A
CR: Carriage Return, U+000D
so you need to try to use
"string".split("\r\n");
Use scanner object, instead of worrying about chars/bytes.
One Solution is to Split using "\n" and neglect empty Strings
List<String> lines = text.split("\n");
for(String line : lines) {
line = line.trim();
if(line != "") {
System.out.println(line);
}
}

How to change "\\r\\n" to line separator in java

I am working on a school project to build a pseudo terminal and file system. The terminal is scanning System.in and pass the string to controller.
Input to console: abc\r\nabc\r\nabc
Here is the code I tried
Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"));
System.out.print(input);
I want java to treat the \r\n I typed to console as a line separator, not actually \ and r.
What it does now is print the input as is.
Desired Ouput:
abc
abc
abc
UPDATE: I tried input = StringEscapeUtils.unescapeJava(input); and it solved the problem.
You need to double-escape the regexes in java (once for the regex backslash, once for the Java string). You dont want a linebreak (/\n/, "\\n"), but a backslash (/\\/) plus a "n": /\\n/, "\\\\n". So this should work:
input.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));
For a more broad handling of escape sequences see How to unescape a Java string literal in Java?
If your input has the string '\r\n', try this
Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"))
For consistent behaviour I would replace \\r with \r and \\n with \n rather than replace \\r\\n with the newline as this will have different behaviour on different systems.
You can do
input = systemIn.nextLine().replaceAll("\\\\r", "\r").replaceAll("\\\\n", "\n");
nextLine() strips of the newline at the end. If you want to add a line separator you can do
input = systemIn.nextLine() + System.getProperty("line.separator");
if you are using println() you don't need to add it back.
System.out.println(systemIn.nextLine()); // prints a new line.
As it was mentioned by r0dney, the Bergi's solution doesn't work.
The ability to use some 3rd party libraries is good, however for a person who studies it is better to know the theory, because not for every problem exists some 3rd party library.
Overload project with tons of 3rd party libraries for tasks which can be solved in one line code makes project bulky and not easy maintainable. Anyway here is what's working:
content.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));
Unless you are actually typing \ and r and \ and n into the console, you don't need to do this at all: instead you have a major misunderstanding. The CR character is represented in a String as \r but it consists of only one byte with the hex value 0xD. And if you are typing backslashes into the console, the simple answer is "don't". Just hit the Enter key: that's what it's for. It will transmit the CR byte into your code.

Categories