Bash 使用 ProcessBuilder 输出到文件的命令不起作用
Bash command to output to file using ProcessBuilder not working
所以,我几乎有以下代码可以使用 ProcessBuilder 将一些文本写入文件:
val requestStringBody = "{\"transfers\": [{\"amount\": 100, \"name\": \"Steve Rogers\", \"taxId\": \"330.731.970-10\",\"bankCode\": \"001\",\"branchCode\": \"1234\",\"accountNumber\": \"123456-0\"}]}"
ProcessBuilder("cmd", "/c", ".\git-bash.lnk", "-c", "echo -n \"$requestStringBody\" >> message.txt")
.directory(File(My Path))
.start()
.waitFor()
由于一些 windows 问题,我不得不使用 git-bash.lnk。
我尝试使用与 requestBodyString 不同的变量执行相同的命令,但它运行良好,这使我相信该字符串有问题,但我就是想不通是什么。
编辑:使用 File(fileName).writeText(fileContent).
解决
您的实际问题可能来自于您在命令行中嵌入的字符串包含双引号并且弄乱了引号(Windows 命令行上的引号也是一团糟)。
也就是说,这看起来是一种非常复杂的将文本写入文件的方式...正如@VGR 所写,您最好只使用常规 API 来写入 Java 中的文件。
例如使用 Kotlin 1.5 的 Path.writeText:
val requestStringBody = "{\"transfers\": [{\"amount\": 100, \"name\": \"Steve Rogers\", \"taxId\": \"330.731.970-10\",\"bankCode\": \"001\",\"branchCode\": \"1234\",\"accountNumber\": \"123456-0\"}]}"
Path("message.txt").writeText(requestStringBody)
或旧版本:
File("message.txt").writeText(requestStringBody)
所以,我几乎有以下代码可以使用 ProcessBuilder 将一些文本写入文件:
val requestStringBody = "{\"transfers\": [{\"amount\": 100, \"name\": \"Steve Rogers\", \"taxId\": \"330.731.970-10\",\"bankCode\": \"001\",\"branchCode\": \"1234\",\"accountNumber\": \"123456-0\"}]}"
ProcessBuilder("cmd", "/c", ".\git-bash.lnk", "-c", "echo -n \"$requestStringBody\" >> message.txt")
.directory(File(My Path))
.start()
.waitFor()
由于一些 windows 问题,我不得不使用 git-bash.lnk。
我尝试使用与 requestBodyString 不同的变量执行相同的命令,但它运行良好,这使我相信该字符串有问题,但我就是想不通是什么。
编辑:使用 File(fileName).writeText(fileContent).
解决您的实际问题可能来自于您在命令行中嵌入的字符串包含双引号并且弄乱了引号(Windows 命令行上的引号也是一团糟)。
也就是说,这看起来是一种非常复杂的将文本写入文件的方式...正如@VGR 所写,您最好只使用常规 API 来写入 Java 中的文件。
例如使用 Kotlin 1.5 的 Path.writeText:
val requestStringBody = "{\"transfers\": [{\"amount\": 100, \"name\": \"Steve Rogers\", \"taxId\": \"330.731.970-10\",\"bankCode\": \"001\",\"branchCode\": \"1234\",\"accountNumber\": \"123456-0\"}]}"
Path("message.txt").writeText(requestStringBody)
或旧版本:
File("message.txt").writeText(requestStringBody)