Saving txt document question
Hi guys,
I have a small problem. The problem is that my code (below) is not saving txt files correctly. When it should save in the following format:
Code:
Line 1
Line 2
Line 3
It saves like this:
The code is as follows, if anyone can help it would be much appreciated:
Code:
//Save File Method
private void saveFile() {
if (filepath == null) { saveFileAs(); return; }
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(filepath));
out.write(txt.getText());
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
//Save File As Method
private void saveFileAs() {
if (dFile.showSaveDialog(this) !=
JFileChooser.APPROVE_OPTION) return;
filepath = dFile.getSelectedFile().getPath();
saveFile();
}
Re: Saving txt document question
Add a "\n" at the end of each line, that should make a new-line.
Re: Saving txt document question
Well I did that for the open file and changed it to this:
Code:
private void open(String file) throws Exception {
BufferedReader in = new BufferedReader(
new FileReader(file));
while (in.ready())
txt.append(in.readLine() + "\r\n");
in.close();
filepath = file;
}
I am not sure where to put in the save method...
Re: Saving txt document question
Your txt.getText() method is the key here. Where is this method?
Re: Saving txt document question
Don't reinvent the wheel!
All text components implement a write(...) method. Use that method instead of trying to create your own.
And the suggestion to add "\n" at the end of every line is not appropriate for all platforms.
Re: Saving txt document question
Could anyone possibly post up an example of how to save it another way, possibly by line instead of all at once?
Re: Saving txt document question
It sounds like your txt.getText() method returns the lines without the line breaks. No matter how you write the file, it will all be on one line if getText() returns all the text as a blob.
For example, if you were looping through a list and wanted to collect the values, you could do something like:
Code:
String outString = "";
for(String s : list){
outString += s + "\r\n";
}
Then, when you write outString the way you did in your original post, it should contain the breaks.
You could write the output one line at a time too, with a PrintWriter and println(), but then your code would be less modular (since your file writing and text-getting would be combined).
Writing all at once is fine if the data you're writing is properly formatted to begin with! Good luck :D