实例化和初始化java.nio.files.Path?

时间:2016-03-25 03:05:52

标签: java oop code-organization

我想在我正在创建的一个名为“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找到。

1 个答案:

答案 0 :(得分:3)

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

创建新的nio Path对象:

import java.nio.file.Path;
import java.nio.file.Paths;

Path p = Paths.get("/tmp/myfile");
相关问题