简体   繁体   English

BufferedWriter逐行写入字符串

[英]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: 在我的程序中,我的String看起来像这样:

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. 我正在从单个toString方法编写所有内容。 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: 这是emp类的toString方法:

@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 您需要在将文本写入文件时使用System.lineSeparator()或更改toString()方法以在添加的每行或对象之间添加行分隔符

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. 现在,如果您希望将其写入具有精确格式的文件中,以便在文件的下一行中显示,则必须单独给出输入,可以通过将对象添加到ArrayList并迭代它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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