Java Formatter not allowing new line character? - java

So, I've got the following code to write to a file:
Formatter output = ....... // Creating the formatter works, writes to appropriate file.
output.format("%d\n", records.length);
for(GradeRecord gR:records)
{
output.format(gR.toString() + "\n");
}
Only problem is, the output doesn't have newline characters.
Doesn't work if I replace "\n" with "\r", either.
...I don't know why this doesn't work. Output is created and writes correctly. (I see the file created and everything is written in it, except for newline characters.)

you can use the format "%n" to output the platform specific newline using a formatter.

You want to use the correct line break string regardless of what platform it's being run on. You can do this dynamically using
String newline = System.getProperty("line.separator");
So you can later do
output.format(gR.toString() + newline);

You can try using \\n instead of \n

Related

Java print escape characters from text file

I am having ANSI escape-sequences inline in code that works, but I cannot get it to work when reading the same string from at text file.
dOut.writeBytes("\033[0;31;1m> help (?) - Get help\n");
(dOut = DataOutputStream)
This prints red text og black background.
When reading the exact same line from a text file it does not work, it prints the line as pure text.
BufferedReader menuReader = new BufferedReader(new FileReader("help.txt"));
while ((menuLine = menuReader.readLine()) != null) {
dOut.writeBytes(menuLine + "\n");
}
menuReader.close();
Text file has only one line: \033[0;31;1m> help (?) - Get help
Write a parser that recognizes particular patterns and convert them into desired string.
The colouring syntax is usually specific to the shell being used e.g. one syntax might work in Bash Shell on Linux but will fail with Cygwin Bash Shell on Windows. Moreover some terminals might not print all the colours combinations e.g. black background with light grey text sometimes doesn't work.
As per this answer you have to use a unicode syntax. To get red text on white background use below:
String redFg = "\u001B[31m";
String blackBg = "\u001B[40m";
System.out.println(blackBg + redFg + "> help (?) - Get help");
In your file you are using \033 which is an octal value equal to \001B hex. You would have to convert your formatting syntax to the one supported by Java.

"\n" not adding new line when saving the string to text using PrintWriter

I want to print a string to a text using out.print but the \n in the string are not working.
Here is the code:
import java.io.PrintWriter;
public class LetterRevisited{
public static void main(String[] args)throws Exception
{
PrintWriter out = new PrintWriter("Test.txt");
out.println("This is the first line\n" +
"This is the second line" );
out.close();
}
}
But in the saved file no new line is created, all the lines are after each other.
Any idea how to fix this? (beside adding out.println to all lines.)
Edit: I compile and run the code with windows command prompt and open the file with notepad.
Different platforms use different line separators.
Windows use \r\n
Unix-like platforms use \n
Mac now uses \n too, but it used to use \r.
(You can see more information and variants here)
You can get your "local" line separator by using
System.getProperty("line.separator")
e.g.
out.println("Hello" + System.getProperty("line.separator") + "World");
However, it is easier to use %n in a string formatter:
out.printf("Hello%nWorld%n");
If you are targeting a particular platform, you can just use the literal.
If you are using Java 7 then you can use System.lineSeparator()..see if this helps. For older versions of Java you can use - System.getProperty("line.separator")
Example :
System.out.println(System.lineSeparator()+"This is the second line");

System.lineSeparator() returns nothing

What should I see when I use the following?
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
System.out.println("LineSeperator2: "+System.lineSeparator());
I get the following back:
LineSeperator1:
LineSeperator2:
Is it empty? invisible? shouldn there be something like \r or \n?
I use windows 7, eclipse and jdk 1.8.
As you expect, the line separator contains special characters such as '\r' or '\n' that denote the end of a line. However, although they would be written in Java source code with those backslash escape sequences, they do not appear that way when printed. The purpose of a line separator is to separate lines, so, for example, the output of
System.out.println("Hello"+System.lineSeparator()+"World");
is
Hello
World
rather than, say
Hello\nWorld
You can even see this in the output of your code: the output of
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
had an extra blank line before the output of the next statement, because there was a line separator from System.getProperty("line.separator") and another from the use of println.
If you really want to see what the escaped versions of the line separators look like, you can use escapeJava from Apache Commons. For example:
import org.apache.commons.lang3.StringEscapeUtils;
public class LineSeparators {
public static void main(String[] args) {
String ls1 = StringEscapeUtils.escapeJava(System.getProperty("line.separator"));
System.out.println("LineSeperator1: "+ls1);
String ls2 = StringEscapeUtils.escapeJava(System.lineSeparator());
System.out.println("LineSeperator2: "+ls2);
}
}
On my system, this outputs
LineSeparator1: \n
LineSeparator2: \n
Note that I had to run it in the same folder as the .jar file from the Apache download, compiling and running with these commands
javac -cp commons-lang3-3.4.jar LineSeparators.java
java -cp commons-lang3-3.4.jar:. LineSeparators
Printing something afterwards will show the effect:
System.out.println("a" + System.lineSeparator() + "b");
Gives
a
b

Trouble replacing return characters in jTextArea

I'm having trouble replacing return characters in a JTextArea in windows 7.
I have an input textArea that for data storage purposes I want to replace the "\r\n" with a unique string like "#!". Problem is, I can't seem to get it to replace it.
EX of issue:
JTextArea exampleText = new JTextArea("Enter Text",10,3);
String oneLineOfText = exampleText.getText().replace("\r\n","#!");
System.out.println(oneLineOfText);
Input:
Text
Text everywhere
Output:
Text
Text everywhere
Desired Output:
Text#!Text everywhere
I feel like I must be doing something really silly. This works perfectly fine in ubuntu when I use "\n" instead of "\r\n".
As I understand it, \r\n is a Windows line terminator.
Instead of looking for just a single line terminator, you could look for multiples and replace them.
For this you could use a regular expressiong and String#replaceAll, for example...
//String text = "This is\r\na test\r\nfor some text";
String text = "This is\na test\r\nfor some text";
System.out.println(text);
text = text.replaceAll("\r\n|\n", "#!");
System.out.println(text);
Which outputs...
This is
a test
for some text
This is#!a test#!for some text
You should also note, that not all text editors/text files have the \r\n line terminator, but Java does a pretty job of dealing with this...
Don't hard-code the newline character, use the system newline character:
System.getProperty("line.separator");
How do I get a platform-dependent new line character?
open a text file, and save the text of JTextArea in it. Now read the text from the saved text file charater by character by checking the following line,
string variable s="";
if(ch=='\n')
add the #! to the string variable;
finally place this string variable to the output section.

Portable newline transformation in Java

Suppose I have a string, which consists of a few lines:
aaa\nbbb\nccc\n (in Linux) or aaa\r\nbbb\r\nccc (in Windows)
I need to add character # to every line in the string as follows:
#aaa\n#bbb\n#ccc (in Linux) or #aaa\r\n#bbb\r\n#ccc (in Windows)
What is the easiest and portable (between Linux and Windows) way to do it Java ?
Use the line.separator system property
String separator = System.getProperty("line.separator") + "#"; // concatenate the character you want
String myPortableString = "#aaa" + separator + "ccc";
These properties are described in more detail here.
If you open the source code for PrintWriter, you'll notice the following constructor:
public PrintWriter(Writer out,
boolean autoFlush) {
super(out);
this.out = out;
this.autoFlush = autoFlush;
lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
It's getting (and using) the system specific separator to write to an OutputStream.
You can always set it at the property level
System.out.println("ahaha: " + System.getProperty("line.separator"));
System.setProperty("line.separator", System.getProperty("line.separator") + "#"); // change it
System.out.println("ahahahah:" + System.getProperty("line.separator"));
prints
ahaha:
ahahahah:
#
All classes that request that property will now get {line.separator}#
I don't know what exactly you are using, but PrintWriter's printf methods lets you write formatted strings. Withing the string you can use the %n format specifier which will output the platform specific line separator.
System.out.printf("first line%nsecond line");
The output:
first line
second line
(System.out is a PrintStream which also supports this).
As of Java 7 (also noted here) you can also use the method:
System.lineSeparator()
which is the same as:
System.getProperty("line.separator")
to get the system-dependent line separator string.
The description of the method from the official JavaDocs is quoted below:
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".

Categories