In
my previous post, I explained how to split a file path using file separator.
Sometimes, you may want to split the string using file path separator.
What is path
separator?
Path
separator is used to combine list of paths. For example, In linux based systems
‘:’ is used as path separator, on Windows ‘;’ is used as path separator.
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
program splits the file paths into list of file paths based on the file path
separator.
For
the following input
f1\f2\f3;folder1\folder2;users\Krishna
On
Windows system, following application return output array like below.
{"f1\f2\f3",
"folder1\folder2, "users\Krishna"}
FileUtil.java
package com.sample.util; import java.io.File; public class FileUtil { private static final String[] NO_PATHS = {}; public static String[] filePaths(String str) { if (str == null || str.isEmpty()) { return NO_PATHS; } return str.split(File.pathSeparator); } }
FileUtilTest.java
package com.sample.util; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; public class FileUtilTest { @Test public void filePaths_empty_emptyArray() { String[] result = FileUtil.filePaths(""); assertEquals(result.length, 0); } @Test public void filePaths_empty_nullArray() { String[] result = FileUtil.filePaths(null); assertEquals(result.length, 0); } @Test public void filePaths_filePaths_arrayWithfilePaths() { String fileName = "hello.txt"; String[] result = FileUtil.filePaths(fileName); assertEquals(result[0], fileName); } @Test public void fileNames_filePaths_arrayWithFilePaths() { String path1 = "f1" + File.separator + "f2" + File.separator + "f3"; String path2 = "folder1" + File.separator + "folder2"; String path3 = "users" + File.separator + "Krishna"; String paths = new StringBuilder(path1).append(File.pathSeparator).append(path2).append(File.pathSeparator) .append(path3).toString(); String[] result = FileUtil.filePaths(paths); assertEquals(result[0], path1); assertEquals(result[1], path2); assertEquals(result[2], path3); } }
You may like
No comments:
Post a Comment