Strings written to file do not preserve line breaks - java

I am trying to write a String(lengthy but wrapped), which is from JTextArea. When the string printed to console, formatting is same as it was in Text Area, but when I write them to file using BufferedWriter, it is writing that String in single line.
Following snippet can reproduce it:
public class BufferedWriterTest {
public static void main(String[] args) throws IOException {
String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
System.out.println(string);
File file = new File("C:/Users/User/Desktop/text.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(string);
bufferedWriter.close();
}
}
What went wrong? How to resolve this? Thanks for any help!

Text from a JTextArea will have \n characters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is \r\n, as others have mentioned).
I think the best way to do that is to wrap the text into a BufferedReader, which can be used to iterate over the lines, and then use a PrintWriter to write each line out to a file using the platform-specific newline. There is a shorter solution involving string.replace(...) (see comment by Unbeli), but it is slower and requires more memory.
Here is my solution - now made even simpler thanks to new features in Java 8:
public static void main(String[] args) throws IOException {
String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
System.out.println(string);
File file = new File("C:/Users/User/Desktop/text.txt");
writeToFile(string, file);
}
private static void writeToFile(String string, File file) throws IOException {
try (
BufferedReader reader = new BufferedReader(new StringReader(string));
PrintWriter writer = new PrintWriter(new FileWriter(file));
) {
reader.lines().forEach(line -> writer.println(line));
}
}

Please see the following question on how to appropriately handle newlines.
How do I get a platform-dependent new line character?
Basically you want to use
String newLineChar = System.getProperty("line.separator");
and then use the newLineChar instead of "\n"

I just ran your program, and adding a carriage return (\r) before your newline (\n) did the trick for me.
If you want to get a system independent line separator, one can be found in the system propery line.separator
String separator = System.getProperty("line.separator");
String string = "This is lengthy string that contains many words. So" + separator
+ "I am wrapping it.";

If you wish to keep the carriage return characters from a Java string into a file. Just replace each break line character (which is recognized in java as: \n) as per the following statement:
TempHtml = TempHtml.replaceAll("\n", "\r\n");
Here is an code example,
// When Execute button is pressed
String TempHtml = textArea.getText();
TempHtml = TempHtml.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/temp.html"))) {
out.print(TempHtml);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(TempHtml);

If you are using a BufferedWriter, you could also use the .newline() method to re-add the newline based on your platform.
See this related question: Strings written to file do not preserve line breaks

Related

After reading with BufferReader '\n' won't be accepted as a new line char, how to solve this?

I have a large text file I want to format. Say the input file is called inputFile and output file is called outputFile.
This is my code for using BufferedReader and BufferedWriter
Here is my code
public static void readAndWrite(String fileNameToRead, String fileNameToWrite) {
try{
BufferedReader fr = new BufferedReader(
new FileReader(String.format("%s.txt", fileNameToRead)));
BufferedWriter out = new BufferedWriter(
new FileWriter(String.format("%s.txt", fileNameToWrite), true));
String currentTmp = "";
String tmp = "";
String test = "work \nwork";
out.append(test);
while((tmp = fr.readLine()) != null) {
tmp = tmp.trim();
if(tmp.isEmpty()) {
currentTmp = currentTmp.trim();
out.append(currentTmp);
out.newLine();
out.newLine();
currentTmp = "";
} else {
currentTmp = currentTmp.concat(" ").concat(tmp);
}
}
if(!currentTmp.equals("")) {
out.write(currentTmp);
}
fr.close();
out.close();
} catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
public static void main(String[] args) {
String readFile = "inPutFile";
String writeFile = "outPutFile";
readAndWrite(readFile, writeFile);
}
The problem is that the test string inside the code which have '\n' can we converted to a new line with BufferedWriter. But if I put the same string in the text file it would not perform the same.
In a more easy way to see is that I want my input file have this
work\n
work
and output as
work
work
I am using mac, so the separator should be '\n'
work\n
if you see the "\n" in your file, it is not a new line character. It is just two characters.
The trim() method will not remove those characters.
Instead you might have something like:
if (tmp.endsWith("\n")
tmp = tmp.substring(0, tmp.length() - 2);
I am using mac, so the separator should be '\n'
You should use the newline character for the platform. So when writing to your file the code should be:
} else {
currentTmp = currentTmp.concat(" ").concat(tmp);
out.append( currentTmp );
out.newLine();
}
The newline() method will use the appropriate new line String for the platform.
Edit:
You need to understand what an escape character is in Java. When you use:
String text = "test\n"
and write the string to a file, only 5 characters are written to the file, not 6. The "\n" is an escape sequence which will cause the ascii value for the new line character to be added to the file. This character is not displayable so you can't see it in the file.
After #camickr answer, I think I realized the problem. Some how if I have a text in the file like this
work \nwork
The \n won't be treated as a single char ('\n'), rather it has been treated as two chars. I think thats why when the BufferWriter writes the input string it won't treat it as a new line.

How Can I Split a Long String Into Lines At "),"?

Having a bit of a headache trying to parse a text file correctly, it's a pull from mysql database but the data needs to be changed a fair bit before it can be inserted again.
My program is taking a .txt file and parsing it to produce a .txt file, which is simple enough.
The issue is that it is not splitting the file correctly. The file looks as follows (the middle field of each looks strange because I've changed it to random letters to hide the real data):
(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),
I want to split it so that it produces a file like:
(92, 'xxxname',4013),
(93, 'sss-xxx', 4047),
(94, 'xxx-sss', 3841),
And so on...
Current code for parsing is as follows:
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.next();
String[] lines = line.split(Pattern.quote("),"));
for (String aLine : lines) {
logLine(aLine);
}
}
}
public static void logLine(String message) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true),
true);
out.println(message);
out.close();
}
Currently the output I'm getting is roughly on track but more split up than it should be, and of course the split method is removing the ")," which is unnecessary.
Sample of the current output:
*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*
Been playing around for a while and have done a good bit of searching here and elsewhere but out of ideas, any help would be greatly appreciated.
You can use String.replace. There's also no need to create multiple PrintWriters and close the stream every time.
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
while (scanner.hasNext()) {
String line = scanner.next();
out.println(line.replace("),", ")," + System.lineSeparator()));
}
out.close();
}
The answer is simple, this line:
String line = scanner.next();
Should be:
String line = scanner.nextLine();
Thanks for your attempts folks sorry for being dumb

Keep new lines when reading in a file

I'm trying to read in a file and modify the text, but I need to keep new lines when doing so. For example, if I were to read in a file that contained:
This is some text.
This is some more text.
It would just read in as
This is some text.This is some more text.
How do I keep that space? I think it has something to do with the /n escape character. I've seen using BufferReader and FileReader, but we haven't learned that in my class yet, so is there another way? What I've tried is something like this:
if (ch == 10)
{
ch = '\n';
fileOut.print(ch);
}
10 is the ASCII table code for a new line, so I thought Java could recognize it as that, but it doesn't.
In Java 8:
You can read lines using:
List<String> yourFileLines = Files.readAllLines(Paths.get("your_file"));
Then collect strings:
String collect = yourFileLines.stream().filter(StringUtils::isNotBlank).collect(Collectors.joining(" "));
The problem is that you (possibly) want to read your file a line at a time, and then you want to write it back a line at a time (keeping empty lines).
The following source does that, it reads the input file one line at a time, and writes it back one line at a time (keeping empty lines).
The only problem is ... it possibly changes the new line, maybe you are reading a unix file and write a dos file or vice-versa depending on the system you are running in and the source type of the file you a reading.
Keeping the original newline can introduce a lot complexity, read BufferedReader and PrintWriter api docs for more information.
public void process(File input , File output){
try(InputStream in = new FileInputStream(input);
OutputStream out = new FileOutputStream(output)){
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"),true);
PrintWriter writer = new PrintWriter( new OutputStreamWriter(out,"utf-8"));
String line=null;
while((line=reader.readLine())!=null){
String processed = proces(line);
writer.println(processed);
}
} catch (IOException e) {
// Some exception management
}
}
public String proces(String line){
return line;
}
/n should be \n
if (ch == 10)
{
ch = '\n';
fileOut.print(ch);
}
Is that a typo?
ch = '/n';
otherwise use
ch = '\n';

How to write new line character to a file in Java

I have a string that contains new lines. I send this string to a function to write the String to a text file as:
public static void writeResult(String writeFileName, String text)
{
try
{
FileWriter fileWriter = new FileWriter(writeFileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(text);
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println("Error writing to file '"+ writeFileName + "'");}
} //end writeResult function
But when I open the file, I find it without any new lines.
When I display the text in the console screen, it is displayed with new lines. How can I write the new line character in the text file.
EDIT:
Assume this is the argument text that I sent to the function above:
I returned from the city about three o'clock on that
may afternoon pretty well disgusted with life.
I had been three months in the old country, and was
How to write this string as it is (with new lines) in the text file. My function write the string in one line. Can you provide me with a way to write the text to the file including new lines ?
EDIT 2:
The text is originally in a .txt file. I read the text using:
while((line = bufferedReader.readLine()) != null)
{
sb.append(line); //append the lines to the string
sb.append('\n'); //append new line
} //end while
where sb is a StringBuffer
In EDIT 2:
while((line = bufferedReader.readLine()) != null)
{
sb.append(line); //append the lines to the string
sb.append('\n'); //append new line
} //end while
you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:
sb.append(System.lineSeparator()); (for Java 1.7 and 1.8)
or
sb.append(System.getProperty("line.separator")); (Java 1.6 and below)
Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:
String updatedText = text.replaceAll("\n", System.lineSeparator())
but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.
Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.
SIMPLE SOLUTION
File file = new File("F:/ABC.TXT");
FileWriter fileWriter = new FileWriter(file,true);
filewriter.write("\r\n");
The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.
bufferedWriter.write(text + "\n"); This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:
bufferedWriter.write(text);
bufferedWriter.newline();
Split the string in to string array and write using above method (I assume your text contains \n to get new line)
String[] test = test.split("\n");
and the inside a loop
bufferedWriter.write(test[i]);
bufferedWriter.newline();
This approach always works for me:
String newLine = System.getProperty("line.separator");
String textInNewLine = "this is my first line " + newLine + "this is my second
line ";
Put this code wherever you want to insert a new line:
bufferedWriter.newLine();
PrintWriter out = null; // for writting in file
String newLine = System.getProperty("line.separator"); // taking new line
out.print("1st Line"+newLine); // print with new line
out.print("2n Line"+newLine); // print with new line
out.close();
Here is a snippet that gets the default newline character for the current platform.
Use
System.getProperty("os.name") and
System.getProperty("os.version").
Example:
public static String getSystemNewline(){
String eol = null;
String os = System.getProperty("os.name").toLowerCase();
if(os.contains("mac"){
int v = Integer.parseInt(System.getProperty("os.version"));
eol = (v <= 9 ? "\r" : "\n");
}
if(os.contains("nix"))
eol = "\n";
if(os.contains("win"))
eol = "\r\n";
return eol;
}
Where eol is the newline

How to write mutilple lines in a text file by calling same method different time?

I come up with a problem.
This is my method below:
public void someMethod()
{
StringBuilder newFile = new StringBuilder();
String edited = "My String Line";
newFile.append(edited);
newFile.append("\n");
FileWriter fstreamWrite = new FileWriter("transaction.txt");
BufferedWriter out = new BufferedWriter(fstreamWrite);
out.write(newFile.toString());
out.close();
}
And when I am calling this method in my main class more than one time so this code is creating my transaction.txt with a line "My String Line". But when I am to call this method more than one time to write the "My String Line" several time, it just overriding the line and not giving me the output like.
My String Line
My String Line
My String Line
When I call the method 3 times.
Any idea how to write the same line multiple times as by calling the same method multiple times?
I think you want to append to a file . Then you can use the constructor FileWriter(java.io.File,boolean):
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
Hence change the code to :
new FileWriter("transaction.txt",true);
To write a new line to the file , use BufferedWriter#newLine().
Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
It is a bad idea to open a file just to write a few lines there. A better approach is to pass the Writer to your method as argument:
public void someMethod(BufferedWriter writer) throws IOExcpetion {
// setup your data to write
StringBuilder sb = .....
// actually write it
writer.write(sb.toString());
writer.newLine()
}
Once you have this, you can use it in a setting like this:
BufferedWriter bw = null;
try {
bw = .... // open the writer
while (...) {
someMethod(bw);
}
bw.close();
} catch (IOException io) {
// handle IOException here
}
...
finally {
// make sure bw is closed
}

Categories

Resources