Reputation: 31
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);
}
}
Upvotes: 0
Views: 103
Reputation: 142
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();
}
}
});
Upvotes: 2
Reputation: 324088
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.
Upvotes: 4