Java: PrintWriter and newlines in a string - java

My question is pretty straight forward, if I have a single long string with alot of "\n" newlines within it, i.e:
strings = "Hey\nThere\nFriend\n"
And use a PrintWriter in Java to do the following:
PrintWriter save = new PrintWriter("test.txt");
save.println(strings);
save.close();
Will the file I end up with be formatted with the \n? i.e the file will have:
Hey
There
Friend
Or will it have:
Hey\nThere\nFriend
If it's the latter, can someone guide me on how I might change my code (and understanding of how PrintWriter works) to create the former output?

In fact, \n will work but only for Unix based OS. Windows based OS use \r\n as separator.
You should avoid using specific OS line separator if you want to write a portable code.
Favor System.lineSeparator() to not be OS dependent.
Note also that PrintWriter provides println() to achieve a break line that is not OS dependent (even if it is not necessary useful for you use case)

You will get a text file containing a single text line Hey\nThere\nFriend\n followed by your operating system new-line sequence (inserted by println()).
The meaning of \n depends on the operating system and possibly the text editor. On Linux \n usually will be interpreted as new-line sequence but on Windows the new-line sequence is \r\n so most text editors (e.g. native Notepad) will display a single HeyThereFriend line.

On windows platform \n means char(13) +Char(10) you can use
String nl = Character.toString ((char) 13)+Character.toString ((char) 10);
String strings = "Hey"+nl+"There"+nl+"Friend"+nl;
System.out.print(strings);

Related

new line when using DataOutputStream, Android

Im trying to export some data from my database to a file. I m using the DataOutputStream because I need the method writeChars(String r).
The problem is that I cannot find a way to change the line. the "\n" leaves a space but its not changing the line. Is there any way to do it?
If you just want to write text to a file you have chosen the wrong class. DataOuputStream.writeChars always writes characters in UTF-16BE. Use BufferedWriter or PrintWriter instead. PrintWriter.println appends a platform specific line separator to the end of the line. The line separator is defined by the system property line.separator, and is not necessarily a single newline character ('\n'). E.g for Windows "\r\n", for Unix '\n' etc.
You can use a variable like String newLine = System.getProperty("line.separator");
Use this : String nl = System.getProperty("line.separator");

Replacing newline character in UNIX

I'm making a code to replace a newline character from a string. On Windows, when I use
String.replaceAll(System.getProperty("line.separator"), "\\n");
this works fine, but it fails in UNIX.
What should i use in UNIX ?
\n is correct for Unix. Windows uses \r\n and Mac uses \r IIRC.
The problem may lie in the fact that Java, being a multiplatform language, automatically replaces \n with the system's separator. I don't know Java but I assume this is the case.
Edit: If the code you posted is what you're using, I think I see the problem. String is a class. It is also immutable in Java. It should instead be this:
String myStr = "abc\ndef";
myStr = myStr.replaceAll(/* params */);
The text being received probably contained windows line separators, so replacing just the \n character had no effect.
If you don't know the origin of the text (or the text contains a mixture of line separators), the following approach can help. First convert windows and mac line separators into unix separators, then convert the unix separators to the system separator.
final String DOS = "\r\n", NIX = "\n", MAC = "\r";
String converted = original.replace(DOS, NIX)
.replace(MAC, NIX)
.replace(NIX, System.lineSeparator());

Carriage returns/line breaks with \n in strings in Android

I'm writing an Android app where I'm writing a file to disk with one data value per line. Later, such files can be read back into the app, and this simple data format is deserialized back into an array. At the moment, I'm delineating data values/lines in the serialization and deserialization code with \n.
How does Android handle carriage returns and such line breaks? Can I use \n safely in this context?
Its better to use
String lineSep = System.getProperty("line.separator");
Yes, the line separator under Windows is \r\n (CR+LF), on Mac \r and on Linux (Android) \n. Java has a clever reader which returns the line without separator, and a println which uses the platform setting System.getProperty("line.separator").
1 - like the two people before me I say, System.getProperty("line.separator") is your friend.
2 - As android is based on linux it is most likely that the line.separator property is in fact \n
3 - When reading or writing your files use buffered reader and writer an respectively their methods readLine and newLine. You should not have any trouble dealing with input/output files from/for other platforms.

"\n" delimiters issue

I have a stringbuilder object, that a line of data gets added to.
after each line gets added, I append a "\n" on the end to indicate a new line.
this stringbuilder object, finalised, gets written to a flat file.
When I open the flat file in notepad I get a small rectangle after every line and the column formatting is ruined.
When I open the flat file in wordpad, the new line is taken into consideration and the column formatting is perfect.
I have tried all ways I know of removing the new line entry before it gets written, but this removes the formatting when written to the flat file. I need the new line for the formatting of the columns.
how can I output the file with new lines but without using \n?
The Windows way of terminating a line is to use "\r\n", not just "\n".
You can find the "line separator for the current operating system" using the line.separator system property:
String lineSeparator = System.getProperty("line.separator");
...
StringBuilder builder = new StringBuilder();
...
builder.append(lineSeparator);
...
You can get the value for the system your Java program is running on from the system properties
public static String newline = System.getProperty("line.separator");
You should add System.getProperty("line.separator") instead of \n. Since "nodepad", it is \r\n, for MS Windows.
In Windows you should use \n\r. In *NIX (Linux/UNIX/Mac) u should use \n
If you're using Windows, you should be writing \r\n to get it to load properly in Notepad. The \n terminator is a Unix file ending, and Notepad won't parse it properly. Wordpad will convert them for you.
Also I suggest not using Notepad, and looking towards something like Vim.

Handling newline character in input between Windows and Linux

I think this is a standard problem which may have been asked before but I could not get the exact answer so posting the issue.
The issue is that our server is running on a linux box. We access the server over the browser on a window box to enter data into field which is supposed to contain multiple lines which user can enter by pressing the enter key after each line
Abc
Def
GHI
When this input field (this is a text area),is read on the linux machine, we want to split the data based on new line character.
I had three question on this.
Does the incoming data contain "\r\n" or "\n"
If incoming data does contain "\r\n", the linux line.separator property (vm property) would not work for me as it would say "\n" and therefore may leave "\r" in the data.
If "\r" is left in the data, if I open the file on a windows machine, will this mean a newline character?
Finally can anyone tell me the standard way to deal with this issue?
The standard java.io.DataInputStream and java.io.BufferedInputReader both handle this automatically through the readLine() method. You really should not use DataInputStream for this since it does not support character sets correctly and it's readLine() has been deprecated for a long time.
For text output, you can use java.io.PrintWriter in which it's printLn(), and related methods with parameters, output the correct newline sequence for the current platform. java.io.BufferedWriter also handles this correctly and provides a public newLine() method.
Linux uses \n.
Windows uses \r\n.
Therefore, unless you've tweaked something in linux, it should be coming in \n.
You could regex out \r\n and \n and replace with whatever you want to avoid problem 3.
http://en.wikipedia.org/wiki/Newline
Rather than using regular expression, you can also make it simpler by doing something like.
StringBuilder sb=new StringBuilder();
// append your texts here and to go to a new line use
if(System.getProperty("os.name").startsWith("Windows")){
sb.insert("\r\n");
}
else {
sb.insert("\n");
}
So if your local environment is windows , you can have this working locally and will also work if you're deploying to a different linux based environments.
Probably try this?
String[] lines = inputString.split("\r?\n");
Not 100% sure about the syntax but the basic idea of the regex is: "zero or one \r, and exactly one \n". Or, if you just want to normalize the input:
inputString = inputString.replace("\r?\n", "\n");
Doesn't seem very painful to me. ;-)
Thanks for the response guys.. Finally looking at suggestion given by Kevin, we used StringReader and BufferedReader wrapper over it to overcome the issue. We used string reader as data is read as a string from the request.
Hopefully this question helps people in future

Categories