简体   繁体   English

如何将printwriter对象写入文件?

[英]How to write a printwriter object to file?

I have a project and the instructions are a bit unclear. 我有一个项目,说明尚不清楚。 I was given an abstract class (Java) with : public abstract void toTxtFile(PrintWriter outFile); 我得到了一个抽象类(Java),它具有:public abstract void toTxtFile(PrintWriter outFile);

The only other instructions relating to that outFile corresponds with staffMember object which should be written to file. 与该outFile有关的唯一其他指令与应该写入文件的staffMember对象相对应。 I wrote the below but not sure if it is correct 我写了以下内容,但不确定是否正确

public void toTxtFile(PrintWriter outFile) { 公共无效toTxtFile(PrintWriter outFile){

   try 

   {
      FileOutputStream fout = new FileOutputStream("pay.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fout);
      oos.writeObject(outFile);

    }
    catch (IOException e) 
    {  
       throw new RuntimeException("Could not write Exception to file", e);
    }
    catch (Exception e)
    {
        System.out.println("There was an error");
    }
}   

You misunderstood the instructions. 您误解了说明。 A PrintWriter can't be written to a file, and that's not what the (admittedly badly named) method should do. 无法将PrintWriter写入文件,这不是(公认的错误命名)方法所不能做的。

What it should most probably do is to write the state of the StaffMember object to the given PrintWriter. 它最有可能要做的是将StaffMember对象的状态写入给定的PrintWriter。

So, in short, the method should look like 因此,简而言之,该方法应类似于

public void toTxtFile(PrintWriter outFile) {
    outFile.println(this.name);
    outFile.println(this.age);
    ...
}

This is similar to me giving you my phone and asking you to spell your name and address to the phone. 这类似于我给您手机并要求您在手机上拼写您的姓名和地址。 A PrintWriter is just a way to communicate your own personal information to someone else. PrintWriter只是一种将您的个人信息传达给其他人的方法。

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

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