0

iam trying to write texts from jtextarea and should save it as a textfile as it is.But when run the program the texts is writing in a single line not writing line by line.

For Example:

My input:

abcd eghi asdasddkj 

but getting output like this

abcdeghiasdasddkj 

Here is my code:

private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) { try { // TODO add your handling code here: String text = jTextArea1.getText(); File file = new File("D:/sample.txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pl=new PrintWriter(bw); pl.println(text); System.out.println(text); pl.close(); } catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } } 
1

2 Answers 2

4

the texts is writing in a single line not writing line by line

The Document only stores "\n" to represent a new line string. The newline string is different depending on the OS you are using. Some editors are smart enough to recognize multiple new lines strings, others are not so you get the single line.

i am trying to write texts from jtextarea and should save it as a textfile

Don't do the IO yourself.

Instead use the write(...) method provided by the JTextArea API.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok,but how can i modify my codes right now with the capability of writing file line by line
@AbooSidhu, read the JTextArea API. There are methods like getLineCount(), getOffsetStart(), getOffsetEnd(), getText(..) that will allow you do get the text one line at a time from the Document. So you need to create your own loop using all the above information.
2

The answer posted by camickr is a perfect solution. But there is no need to use start and end offset methods. JTextArea.wtite() will handle it. It even takes care of line separator for you.

For the desired output your actionPerformed() should be like this..

but1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String text = jta.getText(); File file = new File("D:/sample.txt"); FileWriter fw; try { fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); jta.write(bw); } catch (Exception e1) { e1.printStackTrace(); } } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.