Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating and Initializing java.nio.files.Path?

I would like to use java.nio.files.Path in a class I'm creating called "DocumentGenerator" but I'm not sure how to instantiate and initialize it when using a constructor that does not pass in another Path object. Here are my class variables and two constructors:

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 = 
}

In the second constructor, savePath and fileName need some manipulation before I put them in my Paths object so I do not want to pass them into it just yet. Instead, I would like to try instantiating and initializing "file" to keep in line with good programming practice. My issue is that according to This Question, Path has no constructor. What would be good programming practice in a case like this? Can it be instantiated and initialized in my constructor without a given path?

My question is not "How do I use java.nio.files.Path?", I can find that from the Java API.

like image 471
Hobopowers Avatar asked Mar 25 '16 03:03

Hobopowers


People also ask

What is Java NIO file paths?

Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java. nio. file.

What is absolute path and relative path in Java?

A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to. A relative path contains the path to the file or directory relative to some other path.


1 Answers

Edit : You don't have to instantiate every attributes of your object within your constructors, if you don't instantiate them they will be equal to null.

To create a new nio Path object :

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

Path p = Paths.get("/tmp/myfile");
like image 136
Benoit Vanalderweireldt Avatar answered Sep 28 '22 12:09

Benoit Vanalderweireldt