最近,我一直专注于Clojure,这是一种进行系统脚本编写的功能语言。直到我突然意识到,将JVM置于其下意味着我仅限于Java的功能。
所以,如何创建符号链接?还是硬链接?我的意思是没有(sh "ln" ...)
。
啊,这确实是一种痛苦。我不确定sh
选项是否很糟糕,实际上...话虽如此,Ant提供了一个符号链接任务,您可以通过柳叶刀以一种对Clojure友好的方式使用它,它最初是由Stuart Halloway引入的Ant包装器在他的《 Programming Clojure》一书中,目前由Leiningen内部使用。如果要查看Leiningen中正在运行的symlink任务,请查看1.3.0发行版中的this line。
您可以使用Java Native Access访问目标主机上的本机库。
简单示例:
(ns jna-test
(:import
(com.sun.jna Native Function)))
(defn symlink [oldpath newpath]
(-> (Function/getFunction "c" "symlink")
(.invoke Integer (to-array [oldpath newpath]))))
也可以使用Clojure包装器:clj-native和clojure-jna
为了使现在发现此问题的任何人受益,在Java SE 7中,您可以使用java.nio.file.Files包创建链接。我认为这就是MichałMarczyk在his comment中指的未来。
public static Path createLink(Path link,
Path existing)
throws IOException
public static Path createSymbolicLink(Path link,
Path target,
FileAttribute<?>... attrs)
throws IOException
java文档教程中的[This page提供了这些示例。
Path newLink = ...;
Path target = ...;
try {
Files.createSymbolicLink(newLink, target);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not support symbolic links.
System.err.println(x);
}
Path newLink = ...;
Path existingFile = ...;
try {
Files.createLink(newLink, existingFile);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not
// support adding an existing
// file to a directory.
System.err.println(x);
}
有点旁注:
当使用Clojure作为系统命令时,如果您使用cake而不是leiningen,则它可以使用持久性JVM,因此您不必为每次运行命令而等待三秒钟来启动JVM。
*蛋糕不是很稳定,所以有时候它的效果要好得多。 (截至2010年9月)
您可以利用对我有用的这个库https://github.com/ToBeReplaced/nio.file
(require '[org.tobereplaced.nio.file :refer [create-symbolic-link! ] :as nio])
(defn createSimLink [ targetPath newLink ]
(let [theName (.getName (File. targetPath))]
(try
(nio/create-symbolic-link! (str newLink "/" theName) targetPath )
(catch Exception e (prn "error " e)))))
(createSimLink "c:/tmp/test.txt" "c:/tmp/myFolder")
需要注意相关特权。例如。要在Emacs / Cider环境中的Windows 7中运行它,需要从管理命令窗口启动emacs,否则它将抱怨“ FileSystemException java.nio.file.FileSystemException:c:\ tmp \ myFolder \ test.txt:A客户端不拥有所需的特权”
(require '[clojure.java.io :as io])
(import '[java.nio.file Files Paths]
'[java.nio.file.attribute FileAttribute])
(def user-home (System/getProperty "user.home"))
(def user-pwd (System/getProperty "user.dir"))
(defn path [p]
(let [expanded (.replaceFirst p "^~" user-home)]
(Paths/get expanded (make-array String 0))))
(defn symlink
[link target & attrs]
(let [link-path (path link)
target-path (path (.getPath (io/file user-pwd target)))]
(Files/createSymbolicLink link-path target-path (into-array FileAttribute attrs))))
这就是我想出的。