Trouble replacing return characters in jTextArea - java

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.

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.

Can't print newline character (\n) in strings returned by String.split in Java

I am writing a Java program in which a tab separated values (TSV) file containing two columns of information is read by a BufferedReader and then split into two components (which will serve as [key,value] pairs in a HashMap later in the program) using String.split("\t"). Let's say the first line of the TSV file is as follows:
Key1\tHello world\nProgramming is cool\nGoodbye
The code shown below would separate this line into "Key1" and "Hello world\nProgramming is cool\nGoodbye":
File file = new File("sample.tsv");
BufferedReader br = new BufferedReader(new FileReader(file));
String s = br.readLine();
String[] tokens = new String[2];
tokens = s.split("\t");
The problem now comes in trying to print the second string (i.e. tokens[1]).
System.out.println(tokens[1]);
The line of code above results in the second string being printed with the newline characters (\n) being ignored. In other words, this is printed...
Hello world\nProgramming is cool\nGoodbye
...instead of this...
Hello worldProgramming is coolGoodbye
If I create a new string with the same text as above and use the String.equals() method to compare the two, it returns false.
String str = "Hello world\nProgramming is cool\nGoodbye";
boolean sameString = str.equals(tokens[1]); // false
Why can't special characters in the strings returned by String.split() be printed properly?
BufferedReader.readLine() read your string as one line, as that's how it's represented in the file. Buffered reader didn't read "\n" as ASCII(10) 0x0A, it read "ASCII(92) 0x9C ASCII(110) 0x6E".
If you type the input file the way you expect to see it with your text editor, it will print the way you expect.
on a unix like system:
echo -e "Hello world\nProgramming is cool\nGoodbye" > InputFile.result_you_want
echo "Hello world\nProgramming is cool\nGoodbye" > InputFile.result_you_get
You could use a program like echo to convert your TSV, but then you will need to split on the "\t" character, ASCII(9) 0x09, and not a literal "\t".
Split takes a regular expression. Escaping that tab character may be interesting.
"\t" or "\\t" may do the trick there.
If this is for work, you may want to use a tool or library to work around having to convert your file with echo.
String parsing in Java with delimeter tab "\t" using split has some suggestions there.
Searching for CSV java API's could be very useful. Most will let you set the delimiter character and information on line ending formats.
because in computer aspect, the text '\n' is not like the binary '\n'.
the first line of ur file, i think is like key1 Hello world\nProgramming\ncool
so it's the it can split the \t,but when it comes to print, it only show the text
'\n' but not the binary '\n' which will make the new Line

Java Formatter not allowing new line character?

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

Unable to split a string

I have a string
Mr praneel PIDIKITI
When I use this regular expression
String[] nameParts = name.split("\\s+");
instead of getting three parts I am only getting two, Mr and Praneel PIDIKITI.
I am unable to split the second string. Does anyone know what could be the problem?
I even used split(" ");.
The problem is I used replaceAll("\\<.*?>", " ").trim(); to convert html into this string and then I am using name.split("\\s+"); to get the name value.
I think it must be something other than space (some special character).
Your code should work. I suspect your input. There could be a non printable junk character between Praneel and PIDIKITI. For example,
String name = "Mr praneel" + (char)1 +"PIDIKITI";
String[] nameParts = name.split("\\s+");
for(String s : nameParts)
System.out.println(s);
Are you sure that there is no junk character between Praneel and PIDIKITI?
Remove non printable characters like this:
// remove non printable characters excluding white space characters
name = name.replaceAll("[^\\p{Print}\\s]","");
If you're parsing HTML, may I recommend JSoup? Its a good HTML parser for java

JAVA email message - clip quoted lines

is there a JAVA library to clip the quoted text from an email message?
If it's an HTML message, I used an HTML parser so far and removed the blockquotes from the DOM tree but I have more trouble with the plain text format.
I tried regex:
emailBody = emailBody.replaceAll("\n>[^\n]*?\n", "\n");
but I'm far from mastering it, so I though there has to be a solution since it's a problem concerning more people I guess.
The code above replaces all lines which are new lines (after \n) and beginning with >, not containing any other new lines as long as there is other content and ending with \n. Also I think replacement should be done from starting from the end of the message, and so on. It's a bit more complicated than just that line of code.
So any help is welcome!
Cheers,
Balázs
Do I get you right that you consider each line that starts with a > char a quoted line?
Here's a quick solution:
String[] lines = emailBody.split("\n");
StringBuilder clippedEmailBuilder = new StringBuilder();
for (String line:lines)
if (!line.startsWith(">"))
clippedEmailBuilder.append(line);
emailBody = clippedEmailBuilder.toString();
I'm not sure what you're trying to do with your RE, but considering every line starting with '>' to be quoted mail text you can filter them out with the following:
emailBody.replaceAll(">.*\n", "")
This will match every line starting with '>' and replace it (including the newline) with an empty string

Categories