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

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.");

Related

Best strategy to add lines of text to a text file

I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.
But now I need to add some content at the end of the list that I created. Like this:
PrintWriter writer = new PrintWriter("File.txt", "UTF-8");
writer.println("Hello");
writer.println("Josh!");
writer.close();
the result is a file like this:
Hello
Josh!
but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?
Hello
Josh!
How are you?
I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?
You could simply use a FileWriter instead, it has an append mode that you can enable:
FileWriter writer = new FileWriter("File.txt");
writer.write("Hello\n");
writer.write("Josh!\n");
writer.close();
writer = new FileWriter("File.txt", true);
writer.append("Great!");
writer.close();
Your suspicions are correct.
You should use try with resources (Java 7+):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
out.println("How are you?");
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here

Writing to a file with accented char

I'm using something like this in a java application to write to a file:
BufferedWriter out = new BufferedWriter(new FileWriter(out1, true)); //where out1 is a File.
When I run it from netBeans the output is good. When I try to run it from the windows command line (the intended use; using the jar) the accented characters go crazy. I think that is have something to do with the chars encoding.
e.g.
(the output file is a HTML one);
I want to write this:
"<p>Inclinação(1):</p>"
Using Win command line, appears this:
<p>Inclina褯(1):</p>
Use OutputStreamWriter with FileOutputStream so you can explicitly specify the Charset.
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out1, true), "UTF-8"));
I believe that you need to specify an encoding, unfortunately FileWriter does not provide any ways to set it, though there are other options such as:
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(out1, true),"UTF-8"));
I resolve this problem using the parameter 8859_1, you can learn more about here
http://www.cafeconleche.org/books/xmljava/chapters/ch03s03.html.
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos, "8859_1"));

Format of the output

I am using eclipse to run my program. My programs gives 1000 lines as output, and I write the output on a text file successfully. The problem is that the output on the text file is not same as on the console. On the console there are separate lines, but on text file all lines are appended as one line.
How to get the same console format in a text file?
You will have to make sure of the following:
When writing a line to a file you are including a line separator character(s), you can get a platform independent line separator using the following
System.getProperty("line.separator");
When viewing the text file, some app's (like notepad) may not display new line characters the same as others
The app you are using to view the file will need to be set to view in a monospaced font (such as Courier New)
completely guessing what you are doing but i think you need to do this.
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
while ( rs.next() ) {
// code to write a line.
bw.write("\r\n");
}
use
bw.write("\r\n");
instead of
bw.newLine();
This is for windows systems POSIX systems do newlines differently i believe.
\n is a new line operator just remember that.
Well if you are using a PrintWriter I would simply do
PrintWriter pw = new PrintWriter(file);
while(...you still have data){
pw.println(<yourString>);
}
you can also append the string "\n" to create a new line manually

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();

Having issues in writing text files

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".

Categories