How to Create directory inside the path that has set? - java

I have convert file into DBF format. But i must save that dbf file into specific folder which has generated when i create directory. The common coding just written like this
import java.io.File;
// demonstrates how to create a directory in java
public class JavaCreateDirectoryExample
{
public static void main(String[] args)
{
File dir = new File("/Users/al/tmp/TestDirectory");
// attempt to create the directory here
boolean successful = dir.mkdir();
if (successful)
{
// creating the directory succeeded
System.out.println("directory was created successfully");
}
else
{
// creating the directory failed
System.out.println("failed trying to create the directory");
}
}
}
But, i would like change "/Users/al/tmp/TestDirectory" into a dynamic state which i take it from the path JFileChooser that i've made. Is there any possibilities to make it done? Thanks a lot

If you want to use the same variable, you can instantiate it again.
File dir = new File("/Users/al/tmp/TestDirectory");
boolean successful = dir.mkdir();
// Here we assign a new value by calling the constructor
dir = new File("/Users/al/tmp/AnotherTestDirectory");
// Next we create the new directory using the same method
boolean successful2 = dir.mkdir();

I'm guessing your quite new to Java. You should get in the habit of reading the API. It is your friend and will help answer these questions.
The JFileChooser can be used to get the selected File which can be used to get the path
JFileChooser API:
getSelectedFile() - Returns the selected file.
File API:
getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
...and some sample code
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getAbsolutePath();
File dir = new File(path);
....
}

Related

How to create a text file inside a specific directory?

I am trying to cretae a file SYS_CONFIG_FILE_NAME inside a specific directory SYS_CONFIG_DIR_NAME. using the below posted code, when i run the java program it creates two directories instead of one directory and one text file inside that directory.
The out put of the below code is
SYS_CONFIG/config.txt. But `config.txt` is not a text file it is just a directory named `config.txt`
i referred also to some question in stackoverflow but i could not find a solution. Please let me know what I am missing?
code:
private final static String SYS_CONFIG_DIR_NAME = "SYS_CONFIG";
private final static String SYS_CONFIG_FILE_NAME = "config.txt";
private static File newSysConfigInstance() throws IOException {
// TODO Auto-generated method stub
File f = new File(SYS_CONFIG_FILE_PATH + "/" + SYS_CONFIG_DIR_NAME + "/" + SYS_CONFIG_FILE_NAME);
f.mkdirs();
f.createNewFile();
return f;
}
I would do it that way, you have always to call createNewFile() to create a new instance of the file if it is not created.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs(); // this to create the directories need for your path.
File file = new File(dir, SYS_CONFIG_FILE_NAME);
if (file.createNewFile()) {
system.out.prinln("file first created");
}else {
// print a message here
}
return file;
You are telling it to make a directory of the form a/b/c if you want a directory of the form a/b then you should give it the directory you want it to create.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs();
return new File(dir, SYS_CONFIG_FILE_NAME);
You don't have to pre-create files before you use them.

Best way of opening a file (and ensuring file is chosen)

I have two seperate methods of opening a file.
The first uses a FileChoser with an additional file type filter.
JFileChooser inFileName = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PCF & TXT Files", "pcf", "txt");
inFileName.setFileFilter(filter);
Component parent = null;
int returnVal = inFileName.showOpenDialog(parent);`
The second uses a JOptionPane but has a loop to ensure the directory chosen exists
String filePath;
File directory;
do{
filePath = JOptionPane.showInputDialog("please enter directory");
directory = new File(filePath);
if (directory.exists()==false){
JOptionPane.showMessageDialog(null,"error with directory");
}
}while(directory.exists()==false);
I'm looking to get the best of both here. To be able to choose a file, using a file filter and also loop that function should that directory not be valid.
I've tried switching around variable names and the various functions in different places but I cant seem to get the loop (".exists" function) to work.
You just need to modify your JFileChooser code to use a loop.
JFileChooser inFileName = new JFileChooser();
File file;
boolean valid = false;
while (!valid) {
int returnVal = inFileName.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = inFileName.getSelectedFile();
valid = file.isDirectory();
else {
valid = returnVal == JFileChooser.CANCEL_OPTION;
}
}
Its worth mentioning that this kind of thing might be better achieved using;
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

JFileChooser returns wrong file name?

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String fileName = fc.getSelectedFile().getName();
String path = (new File(fileName)).getAbsolutePath();
}
The absolute path I get is the concatenation of the project directory and fileName!
JFileChooser.getSelectedFile() return the File object.
Why are you getting the file name and instantiating a new File object again?
Can you try:
fc.getSelectedFile().getAbsolutePath();
That's what getAbsolutePath() does - gets the full path, including drive letter (if you're on Windows), etc. What are you trying to get, just the file name?
After you initialize your File object, you can get just the file name from that, OR you can use JFileChooser.getSelectedFile()
If you're getting /path/to/filefilename but you're expecting /path/to/file/filename then you can add an extra slash to the path as appropriate.
Sure. Because you created new file new File(fileName) using returned filename, that means relative path. Use fc.getSelectedFile().getPath() or fc.getSelectedFile().getAbsolutePath() instead.

set directory to a path in a file

I just want to set the directory to a path I have written in a file before.
Therefore I used :
fileChooser.setCurrentDirectory(new File("path.txt"));
and in path.txt the path is given. But unfortunately this does not work out and I wonder why :P.
I think I got it all wrong with the setCurrentDic..
setCurrentDirectory takes a file representing a directory as parameter. Not a text file where a path is written.
To do what you want, you have to read the file "path.txt", create a File object with the contents that you just read, and pass this file to setCurrentDirectory :
String pathWrittenInTextFile = readFileAsString(new File("path.txt"));
File theDirectory = new File(pathWrittenInTextFile);
fileChooser.setCurrentDirectory(theDirectory);
You have to read the contents of path.txt. Thea easiest way is through commons-io:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File dir = new File(fileContents);
You can also use FileUtils.readFileToString(..)
JFileChooser chooser = new JFileChooser();
try {
// Create a File object containing the canonical path of the
// desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e) {
}

How to create a directory in Java?

How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}

Categories