Must read : Create File using createNewFile() method in java file IO
Find current directory or current path in java
In this post we'll create file in current path (or working path or current directory) using
1) new File(currentPath, fileName);
2) System.getProperty("file.separator") or
File.separator
Program 1 to Create File in current path using new File(currentPath, fileName), File.separator in java file IO
import java.io.File;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class CreateFileInCurrentDirectory {
public static void main(String[] args) {
try {
String fileName = "myFile.txt";
String currentPath = System.getProperty("user.dir");
System.out.println("currentPath = "+ currentPath);
//Now, let's create file using new File(currentPath, fileName) method
File file = new File(currentPath, fileName);
if (file.createNewFile())
System.out.println("File has been created successfully > "
+ (currentPath + File.separator + fileName));
else
System.out.println("File with the given name already exists > "
+ (currentPath + File.separator + fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
currentPath = E:\workspace\FileHandling
File has been created successfully > E:\workspace\FileHandling\myFile.txt
*/
|
Program 2 to Create File in current path using System.getProperty("file.separator") in java file IO
import java.io.File;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class CreateFileInCurrentDirectory {
public static void main(String[] args) {
try {
String fileName = "myFile.txt";
String currentPath = System.getProperty("user.dir");
System.out.println("currentPath = "+ currentPath);
String absoluteFilePath = new String( currentPath + File.separator + fileName);
System.out.println("File will be created in (absoluteFilePath)> "+
absoluteFilePath);
//Now, let's create file in absoluteFilePath
File file = new File(absoluteFilePath);
if (file.createNewFile())
System.out.println("File has been created successfully > "
+ absoluteFilePath);
else
System.out.println("File with the given name already exists > "
+ absoluteFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
currentPath = E:\workspace\FileHandling
File will be created in (absoluteFilePath) > E:\workspace\FileHandling\myFile.txt
File has been created successfully > E:\workspace\FileHandling\myFile.txt
*/
|
In above program, we may use any of the following >
System.getProperty("file.separator") or
File.separator
RELATED LINKS>
Create new File in current or specified directory >
Create File using createNewFile() method in java file IO
Find current directory or current path in java
Find parent Directory in java
Labels:
Core Java
File IO/File handling