Thursday, February 28, 2013

How to create file path in java


This is a sample that creating by path:

package com.saretsout.file;

import java.io.File;
import java.io.IOException;

public class FilePath {

/**
* @param args
*/
public static void main(String[] args) throws IOException{
String filename = "sampleFile.docx";
String finalfile = "";

// to get current directory that user is doing
String workingDir = System.getProperty("user.dir");

// to get the type of os name
String your_os = System.getProperty("os.name").toLowerCase();

// check type of os name
if(your_os.indexOf("win") >= 0){
finalfile = workingDir + "\\" + filename;
  }else if(your_os.indexOf( "nix") >=0 || your_os.indexOf( "nux") >=0){
  finalfile = workingDir + "/" + filename;
  }else{
  finalfile = workingDir + "{others}" + filename;
  }

  System.out.println("Final filepath : " + finalfile);
 
  File file = new File(finalfile);

// check file
  if (file.createNewFile()){
System.out.println("Done");
}else{
System.out.println("File already exists!");
}
}

}

No comments:

Post a Comment