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.
Related
I have a text file that contains data every other line. I want to get the content of every non-empty line. Given the whole text of the file, I first tried using myText.split("\n\n"). To my surprise, it does not work. I'm working on Windows.
Windows uses CRLF as line separators. And you are splitting on LF. That wouldn't work.
A safe way is to use:
System.getProperty("line.separator");
to get the appropriate separator on your OS.
String newLine = System.getProperty("line.separator");
myText.split("(?:" + newLine + ")+");
It might be possible that you are reading a file created on a different OS. Then the above method won't work. A better way would be use a character class with CR and LF, as specified in comments by #Marko:
myText.split("[\r\n]+");
is there any way to print a line in java and then go back to the beginning of that line, i tried using \r however this only prints a new line and does not go back to the original line.
So basically if the user inputs "Hello this is lol"
I want to print all the a's in the sentence (none), all the b's, etc...
eg.)" e "
then"He " --> this however must be on the same line as above and you must be able to see the change.
Is there any way to do this in java?
I ran this on my Mac, which is a FreeBSD underneath:
public static void main (String[] args) {
System.out.println("Hello there\rWho's");
}
It printed out
Who's there
If you are running this on Windows, then I cannot be sure what they'll do, but all *nixes should behave as posted.
This is not really a java question, but has more to do with the behavior of your terminal/console.
You are sending the correct character to return to the beginning of the line '\r' but it sounds like your console is not handling this correctly.
You should also be using the print() and not println() function (or whatever the methods are called on the specific object you are using to write). The println() function will add a '\n' character which will cause a new line to appear.
It depends what you mean by "print a line". If you're talking about the command line of an OS window, then you're going to nee to about output terminal control characters to control the cursor.
It depends very much on which operating system you are using, but there are libraries output that can make it simpler.
You might be able to output the backspace character \b to erase the current line, but it may not work.
For a JUnit test I need a String which consists of multiple lines. But all I get is a single lined String. I tried the following:
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
I also tried \n\r instead of \n. System.getProperty("line.separator") doesn't work too. it produces a \n in String and no carriage return. So how can I solve that?
It depends on what you mean by "multiple lines". Different operating systems use different line separators.
In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.
But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.
The fastest way I know to generate a new-line character in Java is: String.format("%n")
Of course you can put whatever you want around the %n like:
String.format("line1%nline2")
Or even if you have a lot of lines:
String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")
Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.
Do this:
Step 1: Your String
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
Step 2: Just replace all "\n" with "%n" the result looks like this
String str = ";;;;;;%n" +
"Name, number, address;;;;;;%n" +
"01.01.12-16.02.12;;;;;;%n" +
";;;;;;%n" +
";;;;;;";
Notice I've just put "%n" in place of "\n"
Step 3: Now simply call format()
str=String.format(str);
That's all you have to do.
Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");
Thanks for your answers. I missed that my data is stored in a List<String> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.
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.
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