简体   繁体   English

Bash 命令 output 到文件使用 ProcessBuilder 不工作

[英]Bash command to output to file using ProcessBuilder not working

So, I pretty much have the below code to write some text to a file using ProcessBuilder:所以,我几乎有以下代码使用 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()

I had to use the git-bash.lnk due to some windows issues.由于一些 windows 问题,我不得不使用 git-bash.lnk。

I've tried the same command using a different variable as the requestBodyString and it works fine, which leads me to believe that that string has an issue with it, but I just cant figured out what.我已经尝试使用与 requestBodyString 不同的变量来执行相同的命令,并且它工作正常,这让我相信该字符串有问题,但我只是想不通是什么。

EDIT: Solved it using File(fileName).writeText(fileContent).编辑:使用 File(fileName).writeText(fileContent) 解决了它。

Your actual problem probably comes from the fact that the string you are embedding in your command line contains double quotes and that messes up quoting (also quoting on Windows command line is a mess).您的实际问题可能来自于您在命令行中嵌入的字符串包含双引号并且弄乱了引号(在 Windows 命令行上引用也是一团糟)。

That being said, this looks like a very convoluted way to write text to a file... as @VGR wrote, you would be better off just using regular APIs to write to files in Java.话虽这么说,这看起来是一种非常复杂的将文本写入文件的方式......正如@VGR 所写,你最好只使用常规 API 来写入 Java 中的文件。

For instance using Kotlin 1.5's Path.writeText :例如使用 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)

Or with older versions:或者使用旧版本:

File("message.txt").writeText(requestStringBody)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM