Skip to content

Instantly share code, notes, and snippets.

@am4dr
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save am4dr/23799f101367b1615e83 to your computer and use it in GitHub Desktop.

Select an option

Save am4dr/23799f101367b1615e83 to your computer and use it in GitHub Desktop.
Pathを任意のセパレータを用いて文字列化する。JavaとStreamによる方法。
import java.nio.file.Path
import java.nio.file.Paths
def p = Paths.get('aaa', 'bbb', 'ccc').resolve('xxx/yyy/zzz/')
assert p as String == /aaa\bbb\ccc\xxx\yyy\zzz/
import java.util.stream.*
def pathToString(Path path, String separator = '/', boolean startsWithSeparator = false) {
StreamSupport.stream(path.spliterator(), false)
.map{ it.toString() }
.collect(Collectors.joining(separator, (startsWithSeparator ? separator : ''), ''))
}
assert pathToString(p, '/', true) == '/aaa/bbb/ccc/xxx/yyy/zzz'
assert pathToString(p, '/', false) == 'aaa/bbb/ccc/xxx/yyy/zzz'
assert pathToString(p, '::', false) == 'aaa::bbb::ccc::xxx::yyy::zzz'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment