File
separator is used to construct file path. ‘/’ is the file separator in windows
and ‘\’ is the file separator in Linux,
For Example
For
the files f1, f2 and f3, the path looks like
f1/f2/f3
in Windows
f1\f2\f3
in Linux environment.
Following
application is used to take list of file names as input and construct the path
as output.
FileUtil.java
package com.sample.util; import java.io.File; public class FileUtil { private static final String EMPTY_STR = ""; public static String constructPath(String[] fileNames){ if(fileNames == null || fileNames.length == 0){ return EMPTY_STR; } StringBuilder pathBuilder = new StringBuilder(); for(String fileName : fileNames){ pathBuilder.append(fileName).append(File.separator); } String path = pathBuilder.toString(); return path.substring(0, path.length()-1); } }
FileUtilTest.java
package com.sample.util; public class FileUtilTest { public static void main(String[] args) { String[] fileNames = { "f1", "f2", "f3" }; String path = FileUtil.constructPath(fileNames); System.out.println(path); } }
File
path separator is used to combine list of file paths. ‘;’ is the file path
separator in Windows, where as ‘:’ is the file path separator in Linux.
For
example,
On
Linux environment, paths can be combined using ‘:’ like below.
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin:
On
Windows based systems, paths can be combined using ‘;’ like below.
C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program
Files (x86)\Java\jdk1.8.0_102\bin;
Following
application takes list of file paths as input and combine the paths using path
separator.
FileUtil.java
package com.sample.util; import java.io.File; public class FileUtil { private static final String EMPTY_STR = ""; public static String constructPath(String[] paths) { if (paths == null || paths.length == 0) { return EMPTY_STR; } StringBuilder pathBuilder = new StringBuilder(); for (String path : paths) { pathBuilder.append(path).append(File.pathSeparator); } String path = pathBuilder.toString(); return path.substring(0, path.length() - File.pathSeparator.length()); } }
FileUtilTest.java
package com.sample.util; import java.io.File; public class FileUtilTest { public static void main(String[] args) { String path1 = "f1" + File.separator + "f2"; String path2 = "f1" + File.separator + "f2" + File.separator + "f3"; String path3 = "folder1" + File.separator + "folder2"; String[] paths = { path1, path2, path3 }; String path = FileUtil.constructPath(paths); System.out.println(path); } }
Sample Output
f1\f2;f1\f2\f3;folder1\folder2
You may like
No comments:
Post a Comment