Having issues in writing text files - java

I am using the FileWriter class to write text files in Java.
The "\n" is not working, so to overcome this I used the BufferedWriter class and its method newLine(). It helped me getting onto next line but alas, it always go on modifying my previous file. I want every time when I run my program a new file to be generated!
Please someone help me on this part. Why is that "\n" not working? What is the possible solution to my problem?
FileWriter write = new FileWriter ("D:/final project/report.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter (write);
bufferedWriter.write("Current Time : " + hour + ":"+ minute + ":" + second + " " + am_pm);
bufferedWriter.newLine();
bufferedWriter.write("Current Date : " + date + "/"+ (month+1) + "/" + year + " d/m/y ");
bufferedWriter.newLine();

You've really got two entirely orthogonal problems here...
I want every time when I run my program a new file to be generated!
Well currently this is how you're creating the FileWriter:
new FileWriter ("D:/final project/report.txt", true);
That's using the constructor overload with an append parameter, which you're setting to true... suggesting you want to append to an existing file.
If you don't want to append to an existing file, why are you specifying true for that parameter? Either specify false instead, or just use an overload which doesn't have that parameter, and overwrites the file by default.
Personally I would strongly advise against using FileWriter directly - I'd use FileOutputStream wrapped in an OutputStreamWriter, so that you can specify the encoding. Otherwise it will use the platform default encoding, which is rarely a good idea IMO. (Personally I tend to use UTF-8 when I have the choice.)
Why is that "\n" not working?
It's working in that it's writing the \n character (U+000A) to the file. But whatever you're using to read that file presumably isn't treating that as a line break - because the line break on Windows is usually \r\n. BufferedWriter.newLine() will use the platform default line break, which is why that's working.

Use the correct line separator:
String lineSep = System.getProperty("line.separator");

You can use FileOutputStream and wrap it in DataOutputStream
FileOutputStream fo=new FileOutputStream("c:/xyz/report.txt");
DataOutputStream ds=new DataOutputStream(fo);
ds.writeBytes("Current Time : " +new Date() );
ds.writeBytes(System.getProperty("line.separator")+"Current Date : " +new Date() );

Java terminates each line with a carriage return and line feed instead of just a line feed. That is Java terminates using "\r\n" instead of "\n".

Related

"\n" not working when exported to .jar file

I have an output file for a program I have written. It is written by a FileWriter and BufferedWriter.
FileWriter errout = new FileWriter(new File("_ErrorList.txt"));
BufferedWriter out = new BufferedWriter(errout);
Later I write to the file using lines similar to.
out.write("Product id:" + idin + " did not fetch any pictures.\n ");
When I simpily run the program in Eclipse, the output file is formatted correctly, with each message being written on a new line. However when I export to a .jar file, it no longer works and puts every message on a single line, as if the "\n" was not working.
Am I using the FileWriter/BufferedWriter incorrectly, or does it not work in a .jar file?
You should not use '\n' directly. Either use out.newLine() to introduce a line break, or wrap the BufferedWriter into a PrintWriter, and use out.println().
This has nothing to do with the .jar file, anyway. More likely is Eclipse being clever and showing you line breaks, while the operating system does not.
One, check that the line separator is valid. Use System.getProperty("line.separator") as provided by #Andrew Thompson.
Another option if you're doing a lot of this writing new lines is to wrap your BufferedWriter in a PrintWriter.
FileWriter errout = new FileWriter(new File("_ErrorList.txt"));
BufferedWriter out = new BufferedWriter(errout);
PrintWriter printWriter = new PrintWriter(out);
printWriter.println("Product id:" + idin + " did not fetch any pictures.");

Java writing to textfiles not completing

I'm using a BufferedWriter to write some data to a textfile. It's faster than using ODBC to write to Access. Code looks something like this:
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath), true));
True is to make the BufferedWriter append, not overwrite.
bw.append(
country + "\t" +
scenario + "\t" +
tempStage + "\t" +
year + "\t" +
tempState
);
It's worked for me in previous projects. New problem: it just craps out in the middle of the line. This is a good line:
SultanateOfBrunei BeeBeeScenario Other 2019
The last line typically looks like this:
SultanateOfBrunei BeeBeeScenario Other 2019 Nondyna
or
Sulta
or even
Su
I put in error handling code to ignore weird incomplete lines like that.
This means not all the data is being written. I can give up one datum, no problem... But it appears to be cutting out more. The simulation runs 1990 to the end of 2020 and it typically craps out somewhere in 2019. Increasing the VM helps a little-- it gets further. But I only have a certain amount of memory!
Any insights?
Thanks!!
Your application is probably not closing the BufferedWriter, and as a result the last part of the output is not being written out to the file.
The structure of your program should be something like this:
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath), true));
try {
// generate output
} finally {
bw.close();
}
Note that this doesn't attempt to handle the I/O exceptions that might arise while opening, writing to or closing the writer. Whether you should do that, and what you should do with any exceptions that you catch depends on the circumstances.
Probably you are not flushing (bw.flush()) the stream before closing it. That should be done to all streams, but it is more critical to buffered ones.
You just need to close the BufferedWriter. If you dont, the last filled buffer might not get written.
Once you're done writing, you should essentially call close() on your BufferedWriter object. This would ensure that the your stream is flushed and consequently closed.

Inserting New Lines when Writing to a Text File in Java

I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??
To create new lines, simply append a newline character to the end of the string:
FileWriter writer = ...
writer.write("The line\n");
Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):
PrintWriter writer = ...
writer.println("The line");
Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.
Or, use a PrintWriter and writer.println().
If you are using BufferedWriter then you can use an inbuilt method :
BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();

why the other part is not printed in the next line?

From the following code :
import java.io.*;
class fileTester {
public static void main( String args[]) throws IOException {
String string = "Suhail" + "\n" + "gupta";
FileOutputStream fos = new FileOutputStream( new File("break.txt"));
byte[] data = string.getBytes();
fos.write( data );
fos.close();
}
}
I expected the output to be :
Suhail
Gupta
int the file created (i.e both the strings in a new line ) but the output is in a single line. Suhail gupta
Why is it so when i have used \n character in between the 2 Strings ?
You shouldn't hard-code the new line character when writing to a file. Use the OS-specific newline String instead:
String newline = System.getProperty("line.separator");
Also, rather than use a FileOutputStream to write raw bytes to a text file, why not wrap it in a PrintStream object so you can easily just use println(...) to do your newlines for you?
I guess you are using notepad to see the file.
End of line character varies from system to system. A more advanced text editor (v.g. Notepad++) will show it correctly, because it tries to find the system that this file was prepared for.
Usually, instead of using always "\n", use
java.lang.System.getProperties().get("line.separator")
If your operating system is windows than you have to use \r\n for a new line, only \n won't work in windows, you can find more details here
This is because for Windows new line is: \r\n. In other OS \n will be good
when you need a new line, the best practice is to use the system newline string, by putting in System.getProperty("line.separator") where you want a line break.
That way, it will use the right new line for the platform you are making the file on (windows/mac/linux).

Newline in FileWriter

How do you produce a new line in FileWriter? It seems that "\n" does not work.
log = new FileWriter("c:\\" + s.getInetAddress().getHostAddress() + ".txt", true);
log.append("\n" + Long.toString(fileTransferTime));
log.close();
The file output of the code above is just a long string of numbers without the new line.
I'll take a wild guess that you're opening the .txt file in Notepad, which won't show newlines with just \n.
Have you tried using your system-specific newline character combination?
log.append(System.getProperty("line.separator") + Long.toString(fileTransferTime));
You should either encapsulate your FileWriter into a PrintWriter if your goal is to have a formated content, println() will help you. Or use the system property line.separator to have a separator adapted to your Operating System.
System.getProperty("line.separator")
Resources :
JavaDoc - PrintWriter
JavaDoc - Properties available on System.getProperty
I'm using "\r\n" and it works great for me. Even when opening .txt document in notepad;)
Try changing \t to \n in the second line.

Categories