[英]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.