简体   繁体   中英

BufferedWriter write string line by line

Hello I am building a program that writes an output to a text file. In my program my String looks like this:

MyName
Addres
Location
Paycheck

But when I write it to a text file it looks like this:

MyName Addres Location Paycheck

I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?

Here's my code:

                               if (file != null) {
                                    FileWriter fileWriter = null;
                                    try {
                                        fileWriter = new FileWriter(file.getAbsolutePath());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    BufferedWriter out = new BufferedWriter(fileWriter);
                                    try {
                                        out.write(emp.toString());
                                        out.close();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }

EDIT:

Here is the toString method for the emp class:

@Override
public String toString() {
    return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
            + myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
             + "\nNet Salary: " + myPaycheck.getNetPay() + "";
}

bufferedwriter API您可以轻松使用“newLine”。

bw.newLine();

You either need to use System.lineSeparator() while writing text to file or change your toString() method to add a line separator between each line or object added

Edit Your code writes your string as separate line only. Try reading the lines from output file and print each line, you will see that the reader treats each detail as separate line. Now if you wish to write it into the file with exact format so that it is shown in next line in file u have to give the inputs separately maybe by adding the objects to an ArrayList and iterating the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM