【问题标题】:Instantiating and Initializing java.nio.files.Path?实例化和初始化 java.nio.files.Path?
【发布时间】:2016-03-25 03:05:51
【问题描述】:

我想在我正在创建的名为“DocumentGenerator”的类中使用 java.nio.files.Path,但我不确定在使用不传入另一个 Path 对象的构造函数时如何实例化和初始化它.这是我的类变量和两个构造函数:

private ArrayList<String> totalOutput;
private ArrayList<String> programInput;
private Scanner in;
private String savePath, fileName;
private Path file;

public DocumentGenerator(Path file) {
    this.programInput = new ArrayList<String>();
    this.totalOutput = new ArrayList<String>();
    this.in = new Scanner(System.in);
    this.file = file;
    this.savePath = "";
    this.fileName = "";
}

public DocumentGenerator(String savePath, String fileName) {
    this.programInput = new ArrayList<String>();
    this.totalOutput = new ArrayList<String>();
    this.in = new Scanner(System.in);
    this.savePath = savePath;
    this.fileName = fileName;
    this.file = 
}

在第二个构造函数中,savePath 和 fileName 在我将它们放入我的 Paths 对象之前需要进行一些操作,所以我还不想将它们传递给它。相反,我想尝试实例化和初始化“文件”以符合良好的编程习惯。我的问题是,根据This Question,Path 没有构造函数。在这种情况下,什么是好的编程实践? 可以在没有给定路径的情况下在我的构造函数中实例化和初始化它吗?

我的问题是不是“我该如何使用 java.nio.files.Path?”,我可以从Java API 找到。

【问题讨论】:

    标签: java oop code-organization


    【解决方案1】:

    编辑: 您不必在构造函数中实例化对象的每个属性,如果您不实例化它们,它们将等于 null。

    创建一个新的 nio Path 对象:

    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    Path p = Paths.get("/tmp/myfile");
    

    【讨论】:

    • 您想从 String 创建一个 Path 实例? Path 没有构造函数,因为它是一个接口,每个文件系统的实现都不同。所以你应该有 this.file = Paths.get(filename);
    • 不能简单地使用:this.file = Paths.get(filename);
    • 好的,我想我现在明白了,如果我在构造函数中没有任何东西,该怎么处理这个对象?然后保持为空。
    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多