0

All I am trying is to implement a simple text-editor. I will keep this simple for now.
I have a text-area and string variable to hold the text and a file to write the contents of the text-area. Intuitively, I think there is a better way (better readability/agile code) to do the same below and this should work for notepad :

 FileWriter out = new FileWriter("filename.txt");
 String sh = jTextArea1.getText();

 for (int i=0; i<sh.length(); i++)
 {
     if (sh.charAt(i) ==  '\n')
          out.write("\r\n");
     else
         out.write(sh.charAt(i));
  }
  out.close();
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
Diljit PR
  • 301
  • 3
  • 14

3 Answers3

0

Use a JTextPane instead of a JTextArea. You need a Document object also. There way there's much more versatility also. Then You can use a one liner to write the entire document to a file

BufferedWriter bw = new BufferedWriter(new FileWriter(file));

textPane.getEditorKit().write(bw, doc, 0, doc.getLength());   <-- one line

javadoc

public abstract void write(OutputStream out,
         Document doc,
         int pos,
         int len)
                    throws IOException,
                           BadLocationException

Writes content from a document to the given stream in a format appropriate for this kind of content handler.

Parameters:
    out - The stream to write to
    doc - The source for the write.
    pos - The location in the document to fetch the content from >= 0.
    len - The amount to write out >= 0.

JTextPane javadoc | EditorKit javadoc | Text Components Tutorial <-- I really recommend this.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0
sh.replace("\n", "\r\n");
out.write(sh);
johnsoe
  • 664
  • 1
  • 5
  • 13
0

Use the read(...) and write(...) methods of a JTextComponent:

FileReader reader = new FileReader( ... );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );

FileWriter writer = new FileWriter( ... );
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
camickr
  • 321,443
  • 19
  • 166
  • 288