简体   繁体   English

一个类可以有自己的专用PrintWriter吗?

[英]Can a class have its own private PrintWriter?

I'm writing a Table class, which stores column name and length information about a relation. 我正在编写一个Table类,该类存储有关关系的列名和长度信息。 The class itself doesn't store the records/tuples, however, as that information is supposed to be directly entered into a txt file via an Insert method. 但是,该类本身不存储记录/元组,因为该信息应该通过Insert方法直接输入到txt文件中。 To make the insert method easier by not recreating a printwriter for every call, can the Table class have its own Printwriter that I can call from Table.insert? 为了不通过为每个调用都重新创建一个printwriter来使插入方法更容易,Table类是否可以拥有自己的Printwriter,我可以从Table.insert中调用它? Basically, 基本上,

public class Table{
    private String tableName;
    private PrintWriter writer;

    public void Table(){
        //get table name
        writer = new PrintWriter(tableName+".txt"); 
    ...}

    public void insert(){
        //get, format, add info to file
        writer.format(formatstring, args);
    }

Are there any flaws with this use of PrintWriter? 使用PrintWriter有任何缺陷吗?

In a word - yes, you can hold a PrintWriter member. 一言以蔽之-是的,您可以持有PrintWriter成员。 Since you're dealing with a filesystem here, there are all sorts of things that could go wrong when creating the PrintWriter . 由于您在这里处理文件系统,因此在创建PrintWriter时可能会出错。 It may be a better practice to open it in a constructor (instead of inlining it in the member's definition) to allow proper exception handling. 最好在构造函数中打开它(而不是将其内联到成员的定义中)以允许适当的异常处理。

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

相关问题 类的对象可以访问其私有方法吗? - Can objects of a class have access to its private methods? 为什么一个类的实例可以访问它自己类型的另一个实例的私有字段? - Why can an instance of a class access private fields of another instance of its own type? 我怎样才能在自己的类中创建一个私有方法来反复使用 - how can i make a private method in to its own class for using over and over 一个类可以拥有自己类型的字段吗? - Is it okay for a class to have a field of its own type 使用getter或direct名称在自己的类中获取私有变量? - Get private variable within its own class with getter or direct with name? 一个有自己线程的类是否也可以有其他类使用的静态方法? - Can a class with its own thread also have static methods that are used by other classes? JPA - 我可以使用 @DiscriminatorValue 创建一个没有自己的表的实体类吗? - JPA - Can I create an Entity class, using an @DiscriminatorValue, that doesn't have its own table? 一个类怎么会有自己类型的成员,这不是无限递归吗? - How can a class have a member of its own type, isn't this infinite recursion? 表单中的字段具有自己的类是否很常见? - Is it common to have for the fields in a form to have its own class? 一个类如何访问自己的类名? - How can a class access its own classname?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM