Friday 26 May 2017

Split file path using system file separator symbol

If you are working in files related application, you may come across the situation, where you want to split the file path using file separator. Following program takes file path as argument and return all the filenames in the path.

FileUtil.java
package com.sample.util;

import java.io.File;
import java.util.regex.Pattern;

public class FileUtil {

 private static final String[] NO_FILES_NAMES = {};

 public static String[] fileNames(String path) {
  if (path == null || path.isEmpty()) {
   return NO_FILES_NAMES;
  }

  String pattern = Pattern.quote(File.separator);
  String[] paths = path.split(pattern);
  return paths;
 }

}

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 fileNames_empty_emptyArray() {
  String[] result = FileUtil.fileNames("");

  assertEquals(result.length, 0);
 }

 @Test
 public void fileNames_empty_nullArray() {
  String[] result = FileUtil.fileNames(null);

  assertEquals(result.length, 0);
 }

 @Test
 public void fileNames_fileName_arrayWithFileName() {
  String fileName = "hello.txt";

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], fileName);
 }

 @Test
 public void fileNames_fileNames_arrayWithFileNames() {
  String fileName = "f1" + File.separator + "f2" + File.separator + "f3";

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], "f1");
  assertEquals(result[1], "f2");
  assertEquals(result[2], "f3");
 }

 @Test
 public void fileNames_fileNamesEndedWithSeparator_arrayWithFileNames() {
  String fileName = "f1" + File.separator + "f2" + File.separator + "f3" + File.separator;

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], "f1");
  assertEquals(result[1], "f2");
  assertEquals(result[2], "f3");
 }

}


No comments:

Post a Comment