问题
I'm enjoying the "better.files
" library in my scala scripts, and one of the common operations (for me) is to create a new file in the same directory as an existing file. My first attempt turns out to be rather verbose and ugly, so I'm wondering if there's a better idiom.
To be specific, here's a bash script that's the equivalent of what I'm wanting to do in scala:
#!/bin/bash
SRC="$HOME/Downloads/some-file.txt"
SRCDIR=$(dirname "$SRC")
DST="$SRCDIR/another-file.txt"
echo "hello!" > "$DST"
In order to accomplish the same thing using the better.files
library, here's what I have so far:
#!/usr/bin/env scalaRunner
import better.files._
import better.files.Dsl._
import java.io.{File => JFile}
val SRC = File.home/"Downloads"/"some-file.txt"
val SRCDIR = SRC.parent
val DST = new JFile(SRCDIR.toJava,"another-file.txt").toScala
DST.overwrite("hello!\n")
It's almost as concise and readable as the bash script, although it would be nice if conversions to and from java.io.File could be hidden. Of course I can always create implicit converters to do just that, but maybe there's a better alternative.
Although there's nothing wrong with explicit conversions, I'm mostly wanting to avoid doing this if there's already a less verbose way to do the equivalent.
For anyone wanting to experiment, both of the above scripts should be executable as-is, assuming the $SRC
file already exists, etc. A working 'scalaRunner
' script can be found here:
https://stackoverflow.com/a/50361608/666886
It assumes that the better-files jar resides in your classpath, as described in the linked answer.
回答1:
how about this:
val src = File.home/"Downloads"/"betterfiles" / "document.jpg"
val srcDir = src.parent
val dst: File = srcDir.createChild("another-file.txt")
dst.overwrite("hello!\n")
来源:https://stackoverflow.com/questions/51387919/what-is-the-recommended-idiom-for-creating-a-new-file-in-the-same-directory-as-a