-
Notifications
You must be signed in to change notification settings - Fork 145
/
File.scala
1429 lines (1199 loc) · 51.1 KB
/
File.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package better.files
import java.io.{File => JFile, _}
import java.net.{URI, URL}
import java.nio.channels._
import java.nio.charset.Charset
import java.nio.file._
import java.nio.file.attribute._
import java.security.MessageDigest
import java.time.Instant
import java.util.function.BiPredicate
import java.util.regex.Pattern
import java.util.zip._
import scala.collection.compat._
import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters._
import scala.util.Properties
import scala.util.matching.Regex
/** Scala wrapper around java.nio.files.Path */
@SerialVersionUID(3435L)
class File private (val path: Path)(implicit val fileSystem: FileSystem = path.getFileSystem) extends Serializable {
def pathAsString: String =
path.toString
/** getResource[...](path) always uses "/" for separator
* https://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
*/
def resourcePathAsString: String =
pathAsString.replace(JFile.separatorChar, '/')
/** @return java.io.File version of this */
def toJava: JFile =
new JFile(path.toAbsolutePath.toString)
/** Name of file
* Certain files may not have a name e.g. root directory - returns empty string in that case
*/
def name: String =
nameOption.getOrElse("")
/** Certain files may not have a name e.g. root directory - returns None in that case */
def nameOption: Option[String] =
Option(path.getFileName).map(_.toString)
/** @return root of this file e.g. '/' for '/dve/null' */
def root: File =
path.getRoot
/** Resolves ../../foo to the fully qualified path */
def canonicalPath: String =
toJava.getAbsolutePath
/** @see canonicalFile */
def canonicalFile: File =
toJava.getCanonicalFile.toScala
/** Return the file name without extension e.g. for foo.tar.gz return foo */
def nameWithoutExtension: String =
nameWithoutExtension(includeAll = true)
/** @param includeAll
* For files with multiple extensions e.g. "bundle.tar.gz"
* nameWithoutExtension(includeAll = true) returns "bundle"
* nameWithoutExtension(includeAll = false) returns "bundle.tar"
*/
def nameWithoutExtension(includeAll: Boolean, linkOptions: File.LinkOptions = File.LinkOptions.default): String =
if (hasExtension(linkOptions)) name.substring(0, indexOfExtension(includeAll)) else name
/** @param includeDot whether the dot should be included in the extension or not
* @param includeAll whether all extension tokens should be included, or just the last one e.g. for bundle.tar.gz should it be .tar.gz or .gz
* @param toLowerCase to lowercase the extension or not e.g. foo.HTML should have .html or .HTML
* @return extension (including the dot) of this file if it is a regular file and has an extension, else None
*/
def extension(
includeDot: Boolean = true,
includeAll: Boolean = false,
toLowerCase: Boolean = true,
linkOptions: File.LinkOptions = File.LinkOptions.default
): Option[String] =
when(hasExtension(linkOptions)) {
val dot = indexOfExtension(includeAll)
val index = if (includeDot) dot else dot + 1
val extension = name.substring(index)
if (toLowerCase) extension.toLowerCase else extension
}
private[this] def indexOfExtension(includeAll: Boolean): Int =
if (includeAll) name.indexOf(".") else name.lastIndexOf(".")
/** Returns the extension if file is a regular file
* If file is unreadable or does not exist, it is assumed to be not a regular file
* See: https://github.com/pathikrit/better-files/issues/89
*/
def hasExtension(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
(isRegularFile(linkOptions) || notExists(linkOptions)) && name.contains(".")
/** Changes the file-extension by renaming this file; if file does not have an extension, it adds the extension
* Example usage file"foo.java".changeExtensionTo(".scala")
*
* If file does not exist (or is a directory) no change is done and the current file is returned
*/
def changeExtensionTo(extension: String, linkOptions: File.LinkOptions = File.LinkOptions.default): File = {
val newName = s"$nameWithoutExtension.${extension.stripPrefix(".")}"
if (isRegularFile(linkOptions)) renameTo(newName) else if (notExists(linkOptions)) File(newName) else this
}
/** return the content type of the file e.g. text/html */
def contentType: Option[String] =
Option(Files.probeContentType(path))
/** Return parent of this file
* NOTE: This API returns null if this file is the root;
* please use parentOption if you expect to handle roots
*/
def parent: File =
parentOption.orNull
/** @return Some(parent) of this file or None if this is the root and thus has no parent */
def parentOption: Option[File] =
Option(path.getParent).map(File.apply)
/** DSL to drop to child */
def /(child: String): File =
path.resolve(child)
/** DSL to drop to child */
def /(child: Symbol): File =
this / child.name
def createChild(
child: String,
asDirectory: Boolean = false,
createParents: Boolean = false,
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): File =
(this / child).createIfNotExists(asDirectory, createParents, attributes, linkOptions)
/** Create this file. If it exists, don't do anything
*
* @param asDirectory If you want this file to be created as a directory instead, set this to true (false by default)
* @param createParents If you also want all the parents to be created from root to this file (false by default)
*/
def createIfNotExists(
asDirectory: Boolean = false,
createParents: Boolean = false,
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type = {
if (exists(linkOptions)) {
this
} else if (asDirectory) {
createDirectories(attributes)
} else {
if (createParents) parent.createDirectories(attributes)
try {
createFile(attributes)
} catch {
case _: FileAlreadyExistsException if isRegularFile(linkOptions) => // We don't really care if it exists already
}
this
}
}
def createFileIfNotExists(
createParents: Boolean = false,
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type =
createIfNotExists(asDirectory = false, createParents, attributes, linkOptions)
def createDirectoryIfNotExists(
createParents: Boolean = false,
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type =
createIfNotExists(asDirectory = true, createParents, attributes, linkOptions)
/** Create this file */
def createFile(attributes: File.Attributes = File.Attributes.default): this.type = {
Files.createFile(path, attributes: _*)
this
}
def exists(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
Files.exists(path, linkOptions: _*)
def notExists(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
Files.notExists(path, linkOptions: _*)
def sibling(name: String): File =
path.resolveSibling(name)
def isSiblingOf(sibling: File): Boolean =
sibling.isChildOf(parent)
def siblings: Iterator[File] =
parent.list.filterNot(_ == this)
def isChildOf(parent: File): Boolean =
parent.isParentOf(this)
/** Check if this directory contains this file
*
* @param strict If strict is false, it would return true for self.contains(self)
* @return true if this is a directory and it contains this file
*/
def contains(file: File, strict: Boolean = true): Boolean =
isDirectory() && (file.path startsWith path) && (!strict || !isSamePathAs(file))
def isParentOf(child: File): Boolean =
contains(child)
def bytes: Iterator[Byte] =
newInputStream().buffered.bytes
/** load bytes into memory - for large files you want to use @see bytes which uses an iterator */
def loadBytes: Array[Byte] =
Files.readAllBytes(path)
def byteArray: Array[Byte] =
loadBytes
/** Create this directory */
def createDirectory(attributes: File.Attributes = File.Attributes.default): this.type = {
Files.createDirectory(path, attributes: _*)
this
}
/** Create this directory and all its parents
* Unlike the JDK, this by default sanely handles the JDK-8130464 bug
* If you want default Java behaviour, use File.LinkOptions.noFollow
*/
def createDirectories(
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type = {
try {
Files.createDirectories(path, attributes: _*)
} catch {
case _: FileAlreadyExistsException if isDirectory(linkOptions) => // work around for JDK-8130464
}
this
}
/** @return characters of this file */
def chars(charset: Charset = DefaultCharset): Iterator[Char] =
newBufferedReader(charset).chars
/** Load all lines from this file
* Note: Large files may cause an OutOfMemory in which case, use the streaming version @see lineIterator
*
* @return all lines in this file
*/
def lines(charset: Charset = DefaultCharset): Iterable[String] =
Files.readAllLines(path, charset).asScala
/** @return number of lines in this file */
def lineCount(charset: Charset = DefaultCharset): Int =
lineIterator(charset).size
/** Iterate over lines in a file (auto-close stream on complete)
* If you want partial iteration use @see lines()
*/
def lineIterator(charset: Charset = DefaultCharset): Iterator[String] =
Files.lines(path, charset).toAutoClosedIterator
/** Similar to string.split(), this returns tokens from the file by given splitter (default is whitespace) */
def tokens(
splitter: StringSplitter = StringSplitter.Default,
charset: Charset = DefaultCharset
): Iterator[String] =
newBufferedReader(charset).tokens(splitter)
/** @return the content of this file as string */
def contentAsString(charset: Charset = DefaultCharset): String =
new String(byteArray, charset)
/** Write lines into this file */
def printLines(
lines: IterableOnce[_],
openOptions: File.OpenOptions = File.OpenOptions.append
): this.type = {
printWriter(openOptions = openOptions).foreach(_.printLines(lines))
this
}
/** For large number of lines that may not fit in memory, use printLines */
def appendLines(lines: Seq[String], charset: Charset = DefaultCharset): this.type = {
Files.write(path, lines.asJava, charset, File.OpenOptions.append: _*)
this
}
/** If you need to specify a charset, use the above version */
def appendLines(lines: String*): this.type =
appendLines(lines)
def appendLine(line: String = "", charset: Charset = DefaultCharset): this.type =
appendLines(Seq(line), charset)
def append(text: String, charset: Charset = DefaultCharset): this.type =
appendByteArray(text.getBytes(charset))
def appendText(text: String, charset: Charset = DefaultCharset): this.type =
append(text, charset)
def appendByteArray(bytes: Array[Byte]): this.type = {
Files.write(path, bytes, File.OpenOptions.append: _*)
this
}
def appendBytes(bytes: Iterator[Byte]): this.type =
writeBytes(bytes, openOptions = File.OpenOptions.append)
/** Write byte array to file. For large contents consider using the writeBytes */
def writeByteArray(
bytes: Array[Byte],
openOptions: File.OpenOptions = File.OpenOptions.default
): this.type = {
Files.write(path, bytes, openOptions: _*)
this
}
def writeBytes(
bytes: Iterator[Byte],
openOptions: File.OpenOptions = File.OpenOptions.default
): this.type = {
outputStream(openOptions).foreach(_.buffered.write(bytes))
this
}
def write(
text: String,
openOptions: File.OpenOptions = File.OpenOptions.default,
charset: Charset = DefaultCharset
): this.type =
writeByteArray(text.getBytes(charset), openOptions)
def writeText(
text: String,
openOptions: File.OpenOptions = File.OpenOptions.default,
charset: Charset = DefaultCharset
): this.type =
write(text, openOptions, charset)
def overwrite(
text: String,
openOptions: File.OpenOptions = File.OpenOptions.default,
charset: Charset = DefaultCharset
): this.type =
write(text, openOptions, charset)
def newRandomAccess(mode: File.RandomAccessMode = File.RandomAccessMode.read): RandomAccessFile =
new RandomAccessFile(toJava, mode.value)
def randomAccess(mode: File.RandomAccessMode = File.RandomAccessMode.read): Dispose[RandomAccessFile] =
newRandomAccess(mode).autoClosed
def newBufferedReader(charset: Charset = DefaultCharset): BufferedReader =
Files.newBufferedReader(path, charset)
def bufferedReader(charset: Charset = DefaultCharset): Dispose[BufferedReader] =
newBufferedReader(charset).autoClosed
def newBufferedWriter(
charset: Charset = DefaultCharset,
openOptions: File.OpenOptions = File.OpenOptions.default
): BufferedWriter =
Files.newBufferedWriter(path, charset, openOptions: _*)
def bufferedWriter(
charset: Charset = DefaultCharset,
openOptions: File.OpenOptions = File.OpenOptions.default
): Dispose[BufferedWriter] =
newBufferedWriter(charset, openOptions).autoClosed
def newFileReader: FileReader =
new FileReader(toJava)
def fileReader: Dispose[FileReader] =
newFileReader.autoClosed
def newFileWriter(append: Boolean = false): FileWriter =
new FileWriter(toJava, append)
def fileWriter(append: Boolean = false): Dispose[FileWriter] =
newFileWriter(append).autoClosed
def newPrintWriter(
autoFlush: Boolean = false,
openOptions: File.OpenOptions = File.OpenOptions.default
): PrintWriter =
new PrintWriter(newOutputStream(openOptions), autoFlush)
def printWriter(
autoFlush: Boolean = false,
openOptions: File.OpenOptions = File.OpenOptions.default
): Dispose[PrintWriter] =
newPrintWriter(autoFlush, openOptions).autoClosed
def newInputStream(openOptions: File.OpenOptions = File.OpenOptions.default): InputStream =
Files.newInputStream(path, openOptions: _*)
def inputStream(openOptions: File.OpenOptions = File.OpenOptions.default): Dispose[InputStream] =
newInputStream(openOptions).autoClosed
def newFileInputStream: FileInputStream =
new FileInputStream(toJava)
def fileInputStream: Dispose[FileInputStream] =
newFileInputStream.autoClosed
def newFileOutputStream(append: Boolean = false): FileOutputStream =
new FileOutputStream(toJava, append)
def fileOutputStream(append: Boolean = false): Dispose[FileOutputStream] =
newFileOutputStream(append).autoClosed
def newScanner(
splitter: StringSplitter = StringSplitter.Default,
charset: Charset = DefaultCharset
): Scanner =
Scanner(newBufferedReader(charset), splitter)
def scanner(
splitter: StringSplitter = StringSplitter.Default,
charset: Charset = DefaultCharset
): Dispose[Scanner] =
newScanner(splitter, charset).autoClosed
def newOutputStream(openOptions: File.OpenOptions = File.OpenOptions.default): OutputStream =
Files.newOutputStream(path, openOptions: _*)
def outputStream(openOptions: File.OpenOptions = File.OpenOptions.default): Dispose[OutputStream] =
newOutputStream(openOptions).autoClosed
def newZipOutputStream(
openOptions: File.OpenOptions = File.OpenOptions.default,
charset: Charset = DefaultCharset
): ZipOutputStream =
new ZipOutputStream(newOutputStream(openOptions), charset)
def zipInputStream(charset: Charset = DefaultCharset): Dispose[ZipInputStream] =
newZipInputStream(charset).autoClosed
def newZipInputStream(charset: Charset = DefaultCharset): ZipInputStream =
new ZipInputStream(newFileInputStream.buffered, charset)
def zipOutputStream(
openOptions: File.OpenOptions = File.OpenOptions.default,
charset: Charset = DefaultCharset
): Dispose[ZipOutputStream] =
newZipOutputStream(openOptions, charset).autoClosed
def newGzipOutputStream(
bufferSize: Int = DefaultBufferSize,
syncFlush: Boolean = false,
append: Boolean = false
): GZIPOutputStream =
new GZIPOutputStream(newFileOutputStream(append), bufferSize, syncFlush)
def gzipOutputStream(
bufferSize: Int = DefaultBufferSize,
syncFlush: Boolean = false,
append: Boolean = false
): Dispose[GZIPOutputStream] =
newGzipOutputStream(bufferSize = bufferSize, syncFlush = syncFlush, append = append).autoClosed
def newGzipInputStream(bufferSize: Int = DefaultBufferSize): GZIPInputStream =
new GZIPInputStream(newFileInputStream, bufferSize)
def gzipInputStream(bufferSize: Int = DefaultBufferSize): Dispose[GZIPInputStream] =
newGzipInputStream(bufferSize).autoClosed
def newFileChannel(
openOptions: File.OpenOptions = File.OpenOptions.default,
attributes: File.Attributes = File.Attributes.default
): FileChannel =
FileChannel.open(path, openOptions.toSet.asJava, attributes: _*)
def fileChannel(
openOptions: File.OpenOptions = File.OpenOptions.default,
attributes: File.Attributes = File.Attributes.default
): Dispose[FileChannel] =
newFileChannel(openOptions, attributes).autoClosed
def newAsynchronousFileChannel(
openOptions: File.OpenOptions = File.OpenOptions.default
): AsynchronousFileChannel =
AsynchronousFileChannel.open(path, openOptions: _*)
def asynchronousFileChannel(
openOptions: File.OpenOptions = File.OpenOptions.default
): Dispose[AsynchronousFileChannel] =
newAsynchronousFileChannel(openOptions).autoClosed
def newWatchService: WatchService =
fileSystem.newWatchService()
def watchService: Dispose[WatchService] =
newWatchService.autoClosed
/** Serialize a object using Java's serializer into this file, creating it and its parents if they do not exist */
def writeSerialized(
obj: Serializable,
bufferSize: Int = DefaultBufferSize,
openOptions: File.OpenOptions = File.OpenOptions.default
): this.type = {
createFileIfNotExists(createParents = true)
.outputStream(openOptions)
.foreach(_.asObjectOutputStream(bufferSize).serialize(obj).flush())
this
}
/** Deserialize a object using Java's default serialization from this file */
def readDeserialized[A](
classLoaderOverride: Option[ClassLoader] = None,
bufferSize: Int = DefaultBufferSize,
openOptions: File.OpenOptions = File.OpenOptions.default
): A =
classLoaderOverride match {
case Some(classLoader) =>
inputStream(openOptions).apply(_.asObjectInputStreamUsingClassLoader(classLoader, bufferSize).deserialize[A])
case _ => inputStream(openOptions).apply(_.asObjectInputStream(bufferSize).deserialize[A])
}
/** register a watch service for given events */
def register(service: WatchService, events: File.Events = File.Events.all): this.type = {
path.register(service, events.toArray)
this
}
def digest(
algorithm: MessageDigest,
visitOptions: File.VisitOptions = File.VisitOptions.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): Array[Byte] = {
listRelativePaths(visitOptions).toSeq.sorted foreach { relativePath =>
val file: File = path.resolve(relativePath)
if (file.isDirectory(linkOptions)) {
algorithm.update(relativePath.toString.getBytes)
} else {
file.newInputStream().withMessageDigest(algorithm).autoClosed.foreach(_.pipeTo(NullOutputStream))
}
}
algorithm.digest()
}
/** Set a file attribute e.g. file("dos:system") = true */
def update(
attribute: String,
value: Any,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type = {
Files.setAttribute(path, attribute, value, linkOptions: _*)
this
}
/** @return checksum of this file (or directory) in hex format */
def checksum(
algorithm: MessageDigest,
visitOptions: File.VisitOptions = File.VisitOptions.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): String =
toHex(digest(algorithm, visitOptions, linkOptions))
def md5(visitOptions: File.VisitOptions = File.VisitOptions.default, linkOptions: File.LinkOptions = File.LinkOptions.default): String =
checksum("MD5", visitOptions, linkOptions)
def sha1(visitOptions: File.VisitOptions = File.VisitOptions.default, linkOptions: File.LinkOptions = File.LinkOptions.default): String =
checksum("SHA-1", visitOptions, linkOptions)
def sha256(
visitOptions: File.VisitOptions = File.VisitOptions.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): String =
checksum("SHA-256", visitOptions, linkOptions)
def sha512(
visitOptions: File.VisitOptions = File.VisitOptions.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): String =
checksum("SHA-512", visitOptions, linkOptions)
/** @return Some(target) if this is a symbolic link (to target) else None */
def symbolicLink: Option[File] =
when(isSymbolicLink)(new File(Files.readSymbolicLink(path)))
/** @return true if this file (or the file found by following symlink) is a directory */
def isDirectory(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
Files.isDirectory(path, linkOptions: _*)
/** @return true if this file (or the file found by following symlink) is a regular file */
def isRegularFile(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
Files.isRegularFile(path, linkOptions: _*)
def isSymbolicLink: Boolean =
Files.isSymbolicLink(path)
def isHidden: Boolean =
Files.isHidden(path)
/** List files recursively up to given depth using a custom file filter */
def list(
filter: File => Boolean,
maxDepth: Int = Int.MaxValue,
visitOptions: File.VisitOptions = File.VisitOptions.default
): Iterator[File] = {
val predicate = new BiPredicate[Path, BasicFileAttributes] {
override def test(p: Path, a: BasicFileAttributes) = filter(p)
}
Files.find(path, maxDepth, predicate, visitOptions: _*)
}
/** Check if a file is locked.
*
* @param mode The random access mode.
* @param position The position at which the locked region is to start; must be non-negative.
* @param size The size of the locked region; must be non-negative, and the sum position + size must be non-negative.
* @param isShared true to request a shared lock, false to request an exclusive lock.
* @return True if the file is locked, false otherwise.
*/
def isLocked(
mode: File.RandomAccessMode,
position: Long = 0L,
size: Long = Long.MaxValue,
isShared: Boolean = false,
linkOptions: File.LinkOptions = File.LinkOptions.default
): Boolean =
try {
usingLock(mode) { channel =>
channel.tryLock(position, size, isShared).release()
false
}
} catch {
case _: OverlappingFileLockException | _: NonWritableChannelException | _: NonReadableChannelException => true
// Windows throws a `FileNotFoundException` if the file is locked (see: https://github.com/pathikrit/better-files/pull/194)
case _: FileNotFoundException if verifiedExists(linkOptions).getOrElse(true) => true
}
/** @see https://docs.oracle.com/javase/tutorial/essential/io/check.html
* @see https://stackoverflow.com/questions/30520179/why-does-file-exists-return-true-even-though-files-exists-in-the-nio-files
*
* @return
* Some(true) if file is guaranteed to exist
* Some(false) if file is guaranteed to not exist
* None if the status is unknown e.g. if file is unreadable
*/
def verifiedExists(linkOptions: File.LinkOptions = File.LinkOptions.default): Option[Boolean] = {
if (exists(linkOptions)) {
Some(true)
} else if (notExists(linkOptions)) {
Some(false)
} else {
None
}
}
def usingLock[U](mode: File.RandomAccessMode)(f: FileChannel => U): U =
newRandomAccess(mode).getChannel.autoClosed.apply(f)
def isReadLocked(position: Long = 0L, size: Long = Long.MaxValue, isShared: Boolean = false) =
isLocked(File.RandomAccessMode.read, position, size, isShared)
def isWriteLocked(position: Long = 0L, size: Long = Long.MaxValue, isShared: Boolean = false) =
isLocked(File.RandomAccessMode.readWrite, position, size, isShared)
def list: Iterator[File] =
Files.list(path)
def children: Iterator[File] = list
def entries: Iterator[File] = list
def listRecursively(visitOptions: File.VisitOptions = File.VisitOptions.default): Iterator[File] =
walk(visitOptions = visitOptions).filterNot(isSamePathAs)
/** Walk the directory tree recursively upto maxDepth
* @return List of children in BFS maxDepth level deep (includes self since self is at depth = 0)
*/
def walk(
maxDepth: Int = Int.MaxValue,
visitOptions: File.VisitOptions = File.VisitOptions.default
): Iterator[File] =
Files.walk(path, maxDepth, visitOptions: _*)
def pathMatcher(syntax: File.PathMatcherSyntax, includePath: Boolean)(pattern: String): PathMatcher =
syntax(this, pattern, includePath)
/** Util to glob from this file's path
*
* @param includePath If true, we don't need to set path glob patterns
* e.g. instead of **.txt we just use *.txt
* @param maxDepth Recurse up to maxDepth
* @return Set of files that matched
*/
def glob(
pattern: String,
includePath: Boolean = true,
maxDepth: Int = Int.MaxValue,
syntax: File.PathMatcherSyntax = File.PathMatcherSyntax.default,
visitOptions: File.VisitOptions = File.VisitOptions.default
): Iterator[File] =
pathMatcher(syntax, includePath)(pattern).matches(this, maxDepth, visitOptions)
/** Util to match from this file's path using Regex
*
* @param includePath If true, we don't need to set path glob patterns
* e.g. instead of **.txt we just use *.txt
* @param maxDepth Recurse up to maxDepth
* @see glob
* @return Set of files that matched
*/
def globRegex(
pattern: Regex,
includePath: Boolean = true,
maxDepth: Int = Int.MaxValue,
visitOptions: File.VisitOptions = File.VisitOptions.default
): Iterator[File] =
glob(pattern.regex, includePath, maxDepth, File.PathMatcherSyntax.regex, visitOptions)
/** More Scala friendly way of doing Files.walk
* Note: This is lazy (returns an Iterator) and won't evaluate till we reify the iterator (e.g. using .toList)
*/
def collectChildren(
matchFilter: File => Boolean,
maxDepth: Int = Int.MaxValue,
visitOptions: File.VisitOptions = File.VisitOptions.default
): Iterator[File] =
walk(maxDepth, visitOptions).filter(matchFilter)
def uri: URI =
path.toUri
def url: URL =
uri.toURL
/** @param returnZeroIfMissing If true, return zeroes for missing files*
* @return file size (for directories, return size of the directory) in bytes
*/
def size(returnZeroIfMissing: Boolean = isDirectory(), visitOptions: File.VisitOptions = File.VisitOptions.default): Long =
walk(visitOptions = visitOptions)
.map({ f =>
try {
Files.size(f.path)
} catch {
case (_: FileNotFoundException | _: NoSuchFileException) if returnZeroIfMissing => 0L
}
})
.sum
def permissions(linkOptions: File.LinkOptions = File.LinkOptions.default): Set[PosixFilePermission] =
Files.getPosixFilePermissions(path, linkOptions: _*).asScala.toSet
def permissionsAsString(linkOptions: File.LinkOptions = File.LinkOptions.default): String =
PosixFilePermissions.toString(permissions(linkOptions).asJava)
def setPermissions(permissions: Set[PosixFilePermission]): this.type = {
Files.setPosixFilePermissions(path, permissions.asJava)
this
}
def addPermission(
permission: PosixFilePermission,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type =
setPermissions(permissions(linkOptions) + permission)
def removePermission(
permission: PosixFilePermission,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type =
setPermissions(permissions(linkOptions) - permission)
/** test if file has this permission */
def testPermission(
permission: PosixFilePermission,
linkOptions: File.LinkOptions = File.LinkOptions.default
): Boolean =
permissions(linkOptions)(permission)
def isOwnerReadable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OWNER_READ, linkOptions)
def isOwnerWritable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OWNER_WRITE, linkOptions)
def isOwnerExecutable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OWNER_EXECUTE, linkOptions)
def isGroupReadable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.GROUP_READ, linkOptions)
def isGroupWritable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.GROUP_WRITE, linkOptions)
def isGroupExecutable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.GROUP_EXECUTE, linkOptions)
def isOthersReadable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OTHERS_READ, linkOptions)
def isOthersWritable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OTHERS_WRITE, linkOptions)
def isOthersExecutable(linkOptions: File.LinkOptions = File.LinkOptions.default): Boolean =
testPermission(PosixFilePermission.OTHERS_EXECUTE, linkOptions)
/** This differs from the above as this checks if the JVM can read this file even though the OS cannot in certain platforms */
def isReadable: Boolean =
toJava.canRead
def isWritable: Boolean =
toJava.canWrite
def isExecutable: Boolean =
toJava.canExecute
def attributes(linkOptions: File.LinkOptions = File.LinkOptions.default): BasicFileAttributes =
Files.readAttributes(path, classOf[BasicFileAttributes], linkOptions: _*)
def posixAttributes(linkOptions: File.LinkOptions = File.LinkOptions.default): PosixFileAttributes =
Files.readAttributes(path, classOf[PosixFileAttributes], linkOptions: _*)
def dosAttributes(linkOptions: File.LinkOptions = File.LinkOptions.default): DosFileAttributes =
Files.readAttributes(path, classOf[DosFileAttributes], linkOptions: _*)
def owner(linkOptions: File.LinkOptions = File.LinkOptions.default): UserPrincipal =
Files.getOwner(path, linkOptions: _*)
def ownerName(linkOptions: File.LinkOptions = File.LinkOptions.default): String =
owner(linkOptions).getName
def group(linkOptions: File.LinkOptions = File.LinkOptions.default): GroupPrincipal =
posixAttributes(linkOptions).group()
def groupName(linkOptions: File.LinkOptions = File.LinkOptions.default): String =
group(linkOptions).getName
def setOwner(owner: String): this.type = {
Files.setOwner(path, fileSystem.getUserPrincipalLookupService.lookupPrincipalByName(owner))
this
}
def setGroup(group: String, linkOptions: File.LinkOptions = File.LinkOptions.default): this.type = {
Files
.getFileAttributeView(path, classOf[PosixFileAttributeView], linkOptions: _*)
.setGroup(fileSystem.getUserPrincipalLookupService.lookupPrincipalByGroupName(group))
this
}
/** Similar to the UNIX command touch - create this file if it does not exist and set its last modification time */
def touch(
time: Instant = Instant.now(),
attributes: File.Attributes = File.Attributes.default,
linkOptions: File.LinkOptions = File.LinkOptions.default
): this.type = {
Files.setLastModifiedTime(createFileIfNotExists(attributes = attributes, linkOptions = linkOptions).path, FileTime.from(time))
this
}
def lastModifiedTime(linkOptions: File.LinkOptions = File.LinkOptions.default): Instant =
Files.getLastModifiedTime(path, linkOptions: _*).toInstant
/** Deletes this file or directory
* Unless otherwise specified, this does not follow symlinks
* i.e. if this is a symlink, only the symlink itself is deleted and not the linked object
*
* @param swallowIOExceptions If this is set to true, any exception thrown is swallowed
*/
def delete(
swallowIOExceptions: Boolean = false,
linkOption: File.LinkOptions = File.LinkOptions.noFollow
): this.type = {
try {
// Note: We call .toList to exhaust the iterator upfront
// since otherwise we wait until the last element of the iterator to close the underlying Stream
// which when doing a DFS may lead to a lot of open file handles for large directories
if (isDirectory(linkOption)) list.toList.foreach(_.delete(swallowIOExceptions, linkOption))
Files.delete(path)
} catch {
case _: IOException if swallowIOExceptions => // e.printStackTrace() //swallow
}
this
}
def renameTo(newName: String): File =
moveTo(path.resolveSibling(newName))
/** Move this to destination similar to unix mv command
* @see moveToDirectory() if you want to move _into_ another directory
*/
def moveTo(
destination: File,
copyOptions: File.CopyOptions = File.CopyOptions(overwrite = false)
): destination.type = {
Files.move(path, destination.path, copyOptions: _*)
destination
}
/** Moves this file into the given directory
* @return the File referencing the new file created under destination
*/
def moveToDirectory(directory: File, linkOptions: File.LinkOptions = File.LinkOptions.default): File = {
require(directory.isDirectory(linkOptions), s"$directory must be a directory")
moveTo(directory / this.name)
}
/** Copy this file to destination similar to unix cp command
*
* @see copyToDirectory() if you want to copy _into_ another directory
*/
def copyTo(destination: File, overwrite: Boolean = false): destination.type =
copyTo(destination, File.CopyOptions(overwrite))
def copyTo(destination: File, copyOptions: File.CopyOptions): destination.type = {
if (isDirectory()) {
Files.walkFileTree(
path,
new SimpleFileVisitor[Path] {
def newPath(subPath: Path): Path = destination.path.resolve(path.relativize(subPath))
override def preVisitDirectory(dir: Path, attrs: BasicFileAttributes) = {
Files.createDirectories(newPath(dir))
super.preVisitDirectory(dir, attrs)
}
override def visitFile(file: Path, attrs: BasicFileAttributes) = {
Files.copy(file, newPath(file), copyOptions: _*)
super.visitFile(file, attrs)
}
}
)
} else {
Files.copy(path, destination.path, copyOptions: _*)
}
destination
}
/** Copies this file into the given directory
* @return the File referencing the new file created under destination
*/
def copyToDirectory(
directory: File,
overwrite: Boolean = false,
linkOptions: File.LinkOptions = File.LinkOptions.default
): File = {
require(directory.isDirectory(linkOptions), s"$directory must be a directory")
copyTo(directory / this.name, overwrite)
}
def symbolicLinkTo(
destination: File,
attributes: File.Attributes = File.Attributes.default
): destination.type = {
Files.createSymbolicLink(path, destination.path, attributes: _*)
destination
}
def linkTo(
destination: File,
symbolic: Boolean = false,
attributes: File.Attributes = File.Attributes.default
): destination.type = {
if (symbolic) {
symbolicLinkTo(destination, attributes)
} else {
Files.createLink(destination.path, path)
destination
}
}
def listRelativePaths(visitOptions: File.VisitOptions = File.VisitOptions.default): Iterator[Path] =
walk(visitOptions = visitOptions).map(relativize)
def relativize(destination: File): Path =
path.relativize(destination.path)
def isSamePathAs(that: File): Boolean =
this.path == that.path
def isSameFileAs(that: File): Boolean =
Files.isSameFile(this.path, that.path)
/** @return true if this file is exactly same as that file
* For directories, it checks for equivalent directory structure
*/
def isSameContentAs(that: File): Boolean =
isSimilarContentAs(that)
/** Almost same as isSameContentAs but uses faster md5 hashing to compare (and thus small chance of false positive)
* Also works for directories
*/
def isSimilarContentAs(that: File): Boolean =
this.md5() == that.md5()
override def equals(obj: Any) = {