How to determine line break in textarea?

P

Perfect Reign

I'm writing an application which has a text area in one of the classes.

I'm saving the information from the text area to a flat file - cvs
formatted. (Don't ask why, it just is so.) Anyway, I need to capture the
line breaks so that I can put a \n in my flat file for reloading the text
into the text area with the line breaks and so my flat file doesn't have
line breaks.

I'm thinking there's got to be some way of searching using firstindexof or
something like that. However, I can't find how to search for a line break
or carriage return (ASCII 10 or 13.)

I'm thinking I'd have to do something like:


String textarea = textComments.getText();
int index = textarea.firstIndexOf( CHR(10) );


Then I'd split the text and create a new string with the \n character.
 
S

Steve W. Jackson

Perfect Reign said:
I'm writing an application which has a text area in one of the classes.

I'm saving the information from the text area to a flat file - cvs
formatted. (Don't ask why, it just is so.) Anyway, I need to capture the
line breaks so that I can put a \n in my flat file for reloading the text
into the text area with the line breaks and so my flat file doesn't have
line breaks.

I'm thinking there's got to be some way of searching using firstindexof or
something like that. However, I can't find how to search for a line break
or carriage return (ASCII 10 or 13.)

I'm thinking I'd have to do something like:


String textarea = textComments.getText();
int index = textarea.firstIndexOf( CHR(10) );


Then I'd split the text and create a new string with the \n character.

By "text area", do you mean JTextArea? If so then perhaps you should
revisit the API JavaDocs, where you'll see methods for obtaining the
information you want. You can get number of lines contained. You can
call getLineStartOffset(int line) to obtain the actual offset into the
complete contents for each line by number. If that doesn't provide the
information you want, then I must not correctly understand your question.

= Steve =
 
P

Perfect Reign

By "text area", do you mean JTextArea? If so then perhaps you should
revisit the API JavaDocs, where you'll see methods for obtaining the
information you want. You can get number of lines contained. You can
call getLineStartOffset(int line) to obtain the actual offset into the
complete contents for each line by number. If that doesn't provide the
information you want, then I must not correctly understand your question.

= Steve =

Yes, JTextArea. I suppose I should have googled that term.

However, getLineStartOffset(int line) give me, "Determines the offset of
the start of the given line," which is about as helpful as anything else in
the API. (Whoever wrote the API has a sick sense of humor because I spend
hours lookinga and get very little useful information. Kind of reminds me
of MSDN.)


Having thought a bit more on this, I'd actually like to replace the
carriage return CHR(13) with a newline character \n. Maybe that'll work.

I'll have to look this up. Something like: replace(mystring, Chr(13), "\n")

--
kai - (e-mail address removed) - www.perfectreign.com

kai:/> format a:
Error: The DOS concept of formatting disk media is screwed.
To format a floppy, use "fdformat /dev/fd0"
and then "mkfs.minix /dev/fd0".
 
D

Daniel Rohe

Do you know the MVC pattern? The JTextArea contains a document and a view.
The document contains the text that is displayed in the view. You can
retrieve the document by getDocument(). This method returns the default
implementation for JTextArea which is a PlainDocument. This stores the text
as a map of lines. But you can also call getText() on the document and get
the text as String. Normally the text has line breaks ("\n") and carriage
returns ("\r") when the user enters the text. But you can then use the
replace method of the text to replace occurences with something you want or
only the empty string. For the map of lines you can call
getDefaultRootElement(). This is the root element and contains a child
element for each line of text. On the root element you can call
getElementCount() to get the number of lines and you can call
getElement(index) to get the specific line. Each element has also a start
and end offset with which you can retrieve the text of the line from the
document.

Daniel


Hm. Here you say you will put a "\n" in the flat file but short after that
you say your flat file has no line breaks?

....
 
P

Perfect Reign

Do you know the MVC pattern? The JTextArea contains a document and a view.
The document contains the text that is displayed in the view. You can
retrieve the document by getDocument(). This method returns the default
implementation for JTextArea which is a PlainDocument. This stores the text
as a map of lines. But you can also call getText() on the document and get
the text as String. Normally the text has line breaks ("\n") and carriage
returns ("\r") when the user enters the text. But you can then use the
replace method of the text to replace occurences with something you want or
only the empty string. For the map of lines you can call
getDefaultRootElement(). This is the root element and contains a child
element for each line of text. On the root element you can call
getElementCount() to get the number of lines and you can call
getElement(index) to get the specific line. Each element has also a start
and end offset with which you can retrieve the text of the line from the
document.

Daniel

Cool. I'll try and digest this.

Hm. Here you say you will put a "\n" in the flat file but short after that
you say your flat file has no line breaks?


Right.

User enters:

Line One.
Line Two.
Third Line.


I will store:

'Line One.\nLine Two.\nThird Line.'


--
kai - (e-mail address removed) - www.perfectreign.com

kai:/> format a:
Error: The DOS concept of formatting disk media is screwed.
To format a floppy, use "fdformat /dev/fd0"
and then "mkfs.minix /dev/fd0".
 
T

Thomas Weidenfeller

Perfect said:
Having thought a bit more on this, I'd actually like to replace the
carriage return CHR(13) with a newline character \n. Maybe that'll work.

If you managed to have carriage returns in the textarea text then you
already screwed up things. Java's internal line separator is '\n'
(newline) only, and nothing else (not to be confused with the
line.separator property, which indicates the operating-system's line
separator, not Java's internal line separator).
I'll have to look this up. Something like: replace(mystring, Chr(13), "\n")

Well, I think you want to have a look at Java's basic syntax. Not that
you need it for the text area problem, but just so you know it in the
future.

Regarding the problem to get the text data line by line, there are
several ways:

The cleanest way would be to get the Document, which should be a
PlainDocument for a JTextArea. Then you could iterate over the Elements
(the Elements of a PlainDocument are the lines). The start/end offsets
for each Element can be used to obtain the corresponding line with the
Document's getText() method.

All this is rather dumb stuff. It makes sense to use this method if you
have a large document, and want to somewhat minimize copying text data
around.

A much simpler way is to get the whole text and split it:

String lines[] = textarea.getText().split("\\n");
for(int i = 0; i < lines.length; i++) {

}

If you don't want the intermediate array, you can burn a few more CPU
cycles and use Readers or better yet the old StringTokenizer.

/Thomas
 
S

Steve W. Jackson

Perfect Reign said:
[ snip ]

By "text area", do you mean JTextArea? If so then perhaps you should
revisit the API JavaDocs, where you'll see methods for obtaining the
information you want. You can get number of lines contained. You can
call getLineStartOffset(int line) to obtain the actual offset into the
complete contents for each line by number. If that doesn't provide the
information you want, then I must not correctly understand your question.

= Steve =

Yes, JTextArea. I suppose I should have googled that term.

However, getLineStartOffset(int line) give me, "Determines the offset of
the start of the given line," which is about as helpful as anything else in
the API. (Whoever wrote the API has a sick sense of humor because I spend
hours lookinga and get very little useful information. Kind of reminds me
of MSDN.)


Having thought a bit more on this, I'd actually like to replace the
carriage return CHR(13) with a newline character \n. Maybe that'll work.

I'll have to look this up. Something like: replace(mystring, Chr(13), "\n")

There's simply no need to do that. First off, don't forget that the
specific end of line sequence varies by platform. But it's very simple
to do it just as I suggested.

You want to know how many lines exist based on when the user added hard
returns. And the last line, which may well not have a hard return, is
still a line. So you call the JTextArea's getLineCount() method. Then,
loop from zero to that value minus one and call getLineStartOffset(int
line) to find out where that line begins, followed by
getLineEndOffset(int line) to find out where it ends. You've already
got access to the text in the inherited getText() methods, one of which
takes a starting offset and length. Or you can use the Document, as
someone else has suggested, which also contains a getText() method
taking two int values.

This is better than searching for any specific character in that it's
not specific to any platform or character. And it's not difficult to do.

= Steve =
 
B

Boudewijn Dijkstra

Perfect Reign said:
I'm writing an application which has a text area in one of the classes.

I'm saving the information from the text area to a flat file - cvs
formatted. (Don't ask why, it just is so.) Anyway, I need to capture the
line breaks so that I can put a \n in my flat file for reloading the text
into the text area with the line breaks and so my flat file doesn't have
line breaks.

What goes wrong when you dump the string from the textarea into the file? If
they both have line breaks, all should be OK!
 
B

Betty

Boudewijn Dijkstra said:
What goes wrong when you dump the string from the textarea into the file? If
they both have line breaks, all should be OK!

I have windows XP Pro, sp1

I have a JTextArea and I save the contents when the window closes via

fos = new FileOutputStream("textfile.txt");
fos.write(DynamicPanel.dynamicOutArea.getText().getBytes());

What I find from a hex dump is that there is a single x0a char
at the end of each line. So the command
type textfile.txt
looks fine, but in the editor
notepad textfile.txt
it is a long single line (dos needs \r\n)

HTH
 
T

Thomas Weidenfeller

Boudewijn said:
What goes wrong when you dump the string from the textarea into the file? If
they both have line breaks, all should be OK!

Nothing would be OK if the operating system does not use a single '\n'
for EOL. You have to convert Java's EOLs (single '\n's) to whatever the
OS uses as EOL (which can be found in the "line.separator" System property).

/Thomas
 
D

Daniel Rohe

....
Right.

User enters:

Line One.
Line Two.
Third Line.


I will store:

'Line One.\nLine Two.\nThird Line.'

That's what the PlainDocument is doing. You could take the text from the
document and save it to file.

Daniel
 
B

Boudewijn Dijkstra

Thomas Weidenfeller said:
Nothing would be OK if the operating system does not use a single '\n' for
EOL. You have to convert Java's EOLs (single '\n's) to whatever the OS uses
as EOL (which can be found in the "line.separator" System property).

I started using line.separator-independant text viewers & editors when I found
out that files from other OS's were using different line breaks.

Anyway, this is nothing that a simple FilterOutputStream can't handle. No
need to do in-memory active search & replace.
 
P

Perfect Reign

Nothing would be OK if the operating system does not use a single '\n'
for EOL. You have to convert Java's EOLs (single '\n's) to whatever the
OS uses as EOL (which can be found in the "line.separator" System property).

/Thomas

That's actually not the issue. I think I'll go with the line count thingy.
Since I develop in both Linux and XP, I'll have to watch for both line
break instances.

Here's an example of what happens with the line breaks.
'Ness','Elliot','Mr.','Treasury Department','(e-mail address removed)','This dude is a real trouble maker!
He will cause us no end to problms.
This is the third line.
Here is the last line.'

Now, hopefully - even with your newsreader wrapping the text it'll show up
as a broken line. I'd rather it be saved like this, so I can parse it
when I read it in...

'Ness','Elliot','Mr.','Treasury Department','(e-mail address removed)','This dude is areal trouble maker!\nHe will cause us no end to problms.\nThis is the third line.\nHere is the last line.'

Hopefully my NG software will force that line to be really long. It should be
181 characters.
 
P

Perfect Reign

A much simpler way is to get the whole text and split it:

String lines[] = textarea.getText().split("\\n");
for(int i = 0; i < lines.length; i++) {

}

If you don't want the intermediate array, you can burn a few more CPU
cycles and use Readers or better yet the old StringTokenizer.


Okay, that worked fine!

String strTempNote = "";
String strLines[] = textNotes.getText().split("\\n");
for(int i = 0; i < lines.length; i++)
{
strNote += strLines + "~~";
}

txtOutput += "'" + strNote + "'";


Thus I end up with...

'Marshall','Holly','Ms.','Kroft','(e-mail address removed)','0 Some Cliff Cave',
'Land of Lost','CA','90000','Holly is lost.~~She is running after Dopey.~~Dopey ate the strawberries.~~'

(I split the line after 'Cave' for the newsgroup.)

But I now have two tilde characters which will allow me to parse on reading into the text area.
 
T

Thomas Weidenfeller

Perfect said:
That's actually not the issue. I think I'll go with the line count thingy.
Since I develop in both Linux and XP, I'll have to watch for both line
break instances.

Ok, for the last time, because it is getting boring:

There is only one line separator inside Java: \n
All Java classes that deal in some way with lines in strings (except I/O
classes) only look for the \n. This is independent on which platform you
run your application. It is always \n inside Java.

You have to convert to and from that separator when you do file and
console I/O. Java's Readers/Writers can do that for you.

It also doesn't make much sense to replace \n with some own line
separator like '~~'. The line separator in Java is already unique.
Replacing it with such a string requires to ensure that the normal text
does not contain the same character sequence. Which is extra work and a
waste of time.

/Thomas
 
R

Ross Bamford

I'm writing an application which has a text area in one of the classes.

I'm saving the information from the text area to a flat file - cvs
formatted. (Don't ask why, it just is so.) Anyway, I need to capture the
line breaks so that I can put a \n in my flat file for reloading the text
into the text area with the line breaks and so my flat file doesn't have
line breaks.

I'm thinking there's got to be some way of searching using firstindexof or
something like that. However, I can't find how to search for a line break
or carriage return (ASCII 10 or 13.)

I'm thinking I'd have to do something like:


String textarea = textComments.getText();
int index = textarea.firstIndexOf( CHR(10) );


Then I'd split the text and create a new string with the \n character.

I'll admit from the start I've not tried to really 'feel' your problem,
but from a scan I'd recommend looking at:

http://java.sun.com/j2se/1.5.0/docs/api/java/text/BreakIterator.html

And maybe the rest of java.text. Perhaps you've already considered and
rejected, apologies if thats the case.

Cheers,
Ross
 
R

Ross Bamford

However, getLineStartOffset(int line) give me, "Determines the offset of
the start of the given line," which is about as helpful as anything else in
the API. (Whoever wrote the API has a sick sense of humor because I spend
hours lookinga and get very little useful information. Kind of reminds me
of MSDN.)

<irrelevant>

Sorry, I just had to comment, because it *hurts*. I belive that the Java
API references, and the wider javadoc/doxygen/et al. idea in general, is
at least partly responsible for the massive take-up of Java. Aside from
one or two (well known) exceptions, the API is (I think) clear, concise,
and eminently accessible.

Of course it's value is reduced somewhat if used as a teaching (or
learning) aid - It is a pure reference resource that happens to
illustrate certain points with examples. If you're looking for specific
examples with a view to learning how to do things, a good place to start
might be:

http://java.sun.com/docs/books/tutorial/


I'm sure the (extensive) Swing tutorials would be of interest.

</irrelevant>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top