Click here to watch in Youtube :
https://www.youtube.com/watch?v=etR2GA_UbFk&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java Tutorial : Java IO (Java File - How to use File separator) |
import java.io.File; import java.io.IOException; /* * Using File.separator construct the file path. */ public class FileDemo1 { public static void main(String[] args) throws IOException { String filename = "myfile.txt"; String workingDirectory = System.getProperty("user.dir"); String filePath = workingDirectory + File.separator + filename; System.out.println("filePath : " + filePath); File file = new File(filePath); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File is already existed!"); } } }
filePath : D:\eclipse\workspace\JavaIODemo\myfile.txt File is created!FileDemo2.java
import java.io.File; import java.io.IOException; /* * Like below construct the file path. * File file = new File(workingDir, filename); */ public class FileDemo2 { public static void main(String[] args) throws IOException { String filename = "myfile.txt"; String workingDirectory = System.getProperty("user.dir"); File file = new File(workingDirectory, filename); System.out.println("filepath : " + file.getAbsolutePath()); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File is already existed!"); } } }
filepath : D:\eclipse\workspace\JavaIODemo\myfile.txt File is already existed!FileDemo3.java
import java.io.File; import java.io.IOException; /* * Check the system OS and create file path manually, not recommend. */ public class FileDemo3 { public static void main(String[] args) throws IOException { String filename = "myfile.txt"; String workingDir = System.getProperty("user.dir"); String absoluteFilePath = ""; String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { // if windows absoluteFilePath = workingDir + "\\" + filename; } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("mac") >= 0) { // if unix or mac absoluteFilePath = workingDir + "/" + filename; } else { // Unknown OS absoluteFilePath = workingDir + "/" + filename; } System.out.println("filepath = " + absoluteFilePath); File file = new File(absoluteFilePath); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists!"); } } }
filepath = D:\eclipse\workspace\JavaIODemo\myfile.txt File already exists!
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_File_separator_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_File_separator_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/882ffbbbc9c8fbb765fb4869059bc3ee253ad31b/BasicJava/JavaIODemo_File_separator_App/?at=master
See also:
No comments:
Post a Comment