Lubos Programming Blog

Lubos Blog about Programming (mainly Java) and Computers

Platform dependent line separator handling in Swing JTextArea

Posted by lubosp on July 25, 2009

If you wish to support platform dependent line separator handling in Swing JTextArea you have to use its read() and write() methods to load or persist the text in the JTextArea. Internally text area remembers the line separators and converts all of them to \n. When the text area is saved into file using write(), the line separators are converted to its original value.

Here is sample code to read the file into text area:

public class MyTextArea extends JTextArea {
...

try {
 FileInputStream fis = new FileInputStream(sourceFile);
 reader = new InputStreamReader(fis);
 read(reader, null);
} finally {
 if (reader != null) {
 try {
 reader.close();
 } catch (Exception ex) {
 // log exception
 }
 }
 }
}

Here is sample code to write text area into a file:

<pre>
<pre>public class MyTextArea extends JTextArea {
...</pre>
</pre>
try {
 writer = new OutputStreamWriter(new FileOutputStream(newFile));
 write(writer);
 } finally {
 if (writer != null) {
 try {
 writer.close();
 } catch (Exception ex) {
 // log exception
 }
 }
 }
}

Do not read the file content using Reader directly to get the content of the file and than call JTextArea.setText() it will not remember the line separator and it will keep the original line separator in the text area, so for example if the file uses Windows line separator \r\n, you will have to press Delete/Backspace key twice to delete line terminator. Pressing Enter key will insert \n and might cause inconsistent line separators (e.g. mixture of \r\n and \n) in the file when saved.

Do not write the file content using Writer directly to save the content of the text area in the file and after call JTextArea.getText(), it  would save the line separators as they are currently in the text area without converting them to the original state.

Check this thread for more info.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: