I am facing a problem with writing a string into a file. I am explaining the scenario. Please help.
I have a text which is read from JTextArea and that text is having line breaks in it. I am trying to write this text into the text file. the characters of the text are being written properly but the line breaks are not getting written into the file. I tried the pattern "\\n" and splitted the text into strings and then tried to write each string into the file by appending a line separator to each string. but later facing some problem with reading the text from the file and displaying in text area. my main aim is to read the text from the JTextArea and write it as it is into a file and then read the content from the file and display in the textArea. here is the code I am trying to read from the file and displaying.
Well, it seems to me that first code snippet would remove any line breaks while reading the content out of the file. You put out line separators only when you read a 0-length String, which is probably never. Why do you think the JTextArea has newlines? It might just be wrapping at the text at the ends of lines, but when you retrieve the text it's just one long String. You could try printing it to the console and seeing what you really have, or checking it out in a debugger if you can.
I Understand what you are saying. yes, the text in the text area can be one long line, but I intentionally added the new lines in the text area content and I am trying to save the same into a file and my intention is to read the content of the file back and put into the text area. here what is happening is while reading the file content, the bufferedreader is considering the new line as the terminator and is not including that into the result. hence the new lines are getting lost. my intention is to avoid bufferreader from stripping newlines and should read the content of the string as it is even if the file is containing new lines in it. these new lines should not be ignored. this is my main intension to achieve
Well, one potential problem I see is if the separator is "\r\n", then this will be stripped off by readLine() but re-added by your code. However, your write method splits the string on "\n" which will discard the new-line but not the carriage-return. then when you write the string out the string will be terminated by "\r\r\n".