java write to the end of file with new line - java

I want to write results to the end of the file using java
FileWriter fStream;
try {
fStream = new FileWriter("recallPresision.txt", true);
fStream.append("queryID=" + queryID + " " + "recall=" + recall + " Pres=" + presision);
fStream.append("\n");
fStream.flush();
fStream.close();
} catch (IOException ex) {
Logger.getLogger(query.class.getName()).log(Level.SEVERE, null, ex);
}
I put "\n" in the statement , it writes to the file but not with new line
I want to print results with new line

The newline sequence is system dependent. On some systems its \n, on others it's \n\r, \r\n, \r or something else entirely different. Luckily, Java has a built in property which allows you to access it:
String newline = System.getProperty("line.separator");

Wrong
fStream.append("\n");
Right
// don't guess the line separator!
fStream.append(System.getProperty("line.separator"));

It does print the newline, what you want is a blank line at the end. Add another \n.

Try using \r\n instead.
Also, you should find that if you open your text file in a rich-text-editor, such as wordpad, your append has actually worked.
Edit: Ignore me. Jeffery and Andrew's answers are much better.

You could also change to:
fStream = new FileWriter("recallPresision.txt", true);
PrintWriter out = new PrintWriter(fStream);
out.println("queryID=" + queryID + " " + "recall=" + recall + " Pres=" + presision);
out.flush();
out.close();
fStream.close();

Related

How do I change the directory a PrintWriter saves to in Java?

My program takes in user input, and puts it into a PrintWriter.
I am unsure of how to change the directory that the PrintWriter saves the text file to. I also need the name of the files to dynamically change based on user input. Here is the code for the PrintWriter:
PrintWriter writer = new PrintWriter(
"ChangeLog" + textField.getText() + textField_1.getText() + textField_9.getText() + ".txt",
"UTF-8");
writer.println("Version Number: " + version);
writer.println("Start Date: " + textField.getText());
writer.println("Start time: " + textField_1.getText());
if (rdbtnYes.isSelected()) {
writer.println("Change was documented in the IT info sheet.");
}
if (rdbtnNo.isSelected()) {
writer.println("Change was NOT documented in the IT info sheet.");
}
writer.println("Budget Implecation(S): " + textField_2.getText());
writer.println("Server/Network Device: " + textField_3.getText());
writer.println("Process Of Changes Made: " + textField_4.getText());
writer.println("Need(s)/Reason(s) for Change: " + textField_5.getText());
writer.println("Issues/Problems: " + textField_6.getText());
writer.println("Outcome/Results: " + textField_7.getText());
writer.println("Notes/Comments/Other Info" + textField_8.getText());
writer.close();
The constructor you are using takes a String argument - denoting a file name.
File names can be just that; or they can include path information. You want a different path - then change the filename to include that path!
See here or this for relative vs. absolute paths.
One way to do this is that you will need to create a FileWriter object and tell it what location will the file sit where you want to write stuff. Then you'll pass your FileWriter object as an argument to the PrintWriter constructor.
See the example below:
FileWriter writer = new FileWriter("d:\\path_to_directory\\report.txt");
PrintWriter printWriter = new PrintWriter (writer);
Hope this helps! :)

Java: BufferdWriter prints String into two lines for no reason?

I am currently writing a "text check" program in Java, but somehow I got stuck whilst creating an unique identifier for every file.
Actually I create an new identifier like this:
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
Also my program creates a new file and opens a BufferedWriter.
Actually when I now try to append (I tried using BufferedWriter#write, too, but it didn't work either.)
If I write this String into the file now, it looks like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4Nj
dGVzdC5zYzA
but it should be in only one line like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4NjdGVzdC5zYzA
At first I thought that it would probably have a problem with me creating a new line after using BufferedWriter#write, so I tried flushing my BufferedWriter before creating a new line. It didn't work either...
PS:
The whole neccessary code:
String name = file.getName().substring(0, ind);
File next = new File(folder.getAbsolutePath(), name+".sc0");
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
try {
next.delete();
next.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(next));
logger.info("Adding compiler identifier to file ...");
writer.write("#Script0:"+identifier);
writer.flush();
writer.newLine();
for(String str : lines) {
writer.newLine();
writer.append(str);
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Strange bug ... Did you delete the file? Please try again!");
return;
}
It's the encoder, not the BufferedWriter. Base-64 encoding uses a line length of (I believe) 72 characters.

How to add a new line after writing a array of characters into a file using JAVA

After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}

Writing to A Text File-Writing To Next Line

I'm appending to a text file but it won't go write to the next line, it keeps writing on the same line. I've tried .println() and PrintWriter.write("\r\n"); I'm not sure what else to do. (Windows System) Any help would be appreciated,
PrintWriter fOut;
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.append("text\n");
fOut.close();
}
catch (IOException ex) {
Logger.getLogger(ScorePredictorFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Assuming that file_name.txt already exists, and you want to write to the next line, I would do:
fOut.append("\r\ntext");
What is "text" in fOut.append("text\n");
if you are doing something like String text = ""; then you need to do it as fOut.append(text + "\n"); Else what you are doing is correct.
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.println("text");
fOut.close();
}
The above code should work because according to the Java doc of the method it does enter the line separator
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
You can check the line.separator property using the following
final String lineSeparator = System.getProperty ( "line.separator" );

Strings are not written to a new line

Following snippet attempts to write the name of directories and files present in some directory to a text file.Each name should be written to a separate line.Instead it prints each name on the same line. Why is it so ?
try {
File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
FileWriter writer = new FileWriter(listFile,true);
Iterator iterator = directoryList.iterator();
while(iterator.hasNext()) {
writer.write((String)iterator.next());
writer.write("\n"); // Did this so each name is on a new line
}
writer.close();
}catch(Exception exc) {
exc.printStackTrace();
}
output:
Where am i making a mistake ?
Whenver you need textual formatting always use PrintWriter.
The right way of doing is to wrap the writer inside a PrintWriter and use println() method, like:
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
If you are using Windows, use \r\n instead of \n.
or for OS-independent, use:
System.getProperty("line.separator");
You should write your next line as "\r\n" if you are on a Windows platform.
The next line for Windows is "\r\n"
The next line for Mac is "\n"
Alternatively, use System.getProperty("line.separator") for your line break. It automatically determines the right line break for the system it is running on. This should be the best practice since Java is expected to perform the same on different OS-es.
If you are going to use BufferedWriter :
File f = new File("C:/file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write("Hello");
bw.newLine(); // new line
bw.write("How are you?");
bw.close();

Categories