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

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.

Related

How to add information to existing text file in java

I am a beginner. I have a text file which already has data and the data can be updated but now i would like to add more data from another GUI form to be added at the end of the data
Now it look like this
name//add/password//postcode//email//hpNo//Buyer
I want to add one more item at the end of the row
name//add/password//postcode//email//hpNo//Buyer//PAYMENT
My current code creates a new data instead of adding it to the last column:
String addcash="";
try
{
File file = new File("MyAccount.txt");
Scanner reader = new Scanner (file);
String line = "", oldtext = "", update = "";
while(reader.hasNextLine())
{
line = reader.nextLine();
String[] text = line.split("//");
accNameTextField.setText(new User().getusername());
if (text[0].equals(accNameTextField.getText())){
String update2 = "//" + addcshComboBox.getSelectedItem();
addcash += accNameTextField.getText() + update2 + System.lineSeparator();
}
else
{
addcash += line + System.lineSeparator();
}
}
reader.close();
FileWriter writer = new FileWriter("MyAccount.txt");
writer.write(addcash);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
Here is the explaination:
To tell the FileWriter that you want to append the text and not to override the existing file you need to add a parameter to the FileWriter constructor, here is the code:
FileWriter writer = new FileWriter("MyAccount.txt", true); // Add the "true" parameter!
writer.write(addcash);
writer.close();
need the system to know that there is data over there and skip to the next line so i added [text] on this part of the code
if (text[0].equals(accNameTextField.getText())){
String update2 = "//" + text[1] +"//"+ text[2] +"//"+ text[3] +"//"+ text[4] +"//"+ text[5] +"//"+text[6] +"//"+addcshComboBox.getSelectedItem();
addcash += accNameTextField.getText() + update2 + System.lineSeparator();

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

Write Java String to file with special encoding

I have got the Java String ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#~€4` which I would like to write to a file with ANSI encoding.
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"windows-1252"));
try {
out.append(str);
} finally {
out.close();
}
Debugger says that str contains ôð¤ Ø$î1<¨ V¸dPÐ ÀH#àÀà¼#~4. As soon as I write it to the output file, the file only contains ?ÒÜ#4. So whats wrong with my method writing to the File?
Sorry for this weird strings - I am trying to rewrite a delphi 7 function in java. These strings are the only samples I have got.
If I run
String text = "ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4";
Writer writer = new OutputStreamWriter(new FileOutputStream("test.txt"), "windows-1252");
writer.append(text);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "windows-1252"));
String line = br.readLine();
br.close();
System.out.println(line.length() + ": '" + line + "' matches " + line.equals(text));
it prints
32: 'ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4' matches true
so no characters are lost in translation.
If I change the encoding to "US-ASCII" I get the following output
32: '??? ?$?1<? V?dP?? ?H#??????#`~?4' matches false

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

java write to the end of file with new line

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

Categories