new String(bytes)在gradle中不起作用

时间:2017-02-18 01:19:35

标签: android-studio intellij-idea gradle groovy

我试图使用

从shell读取输出数据
Slick

当我在groovy脚本中尝试使用该代码时,事实证明这并不算什么。它可以工作。

最后我发现问题应该是新的String(字节),下面的代码在groovy脚本中工作但不在gradle中。

def cmd = "adb shell echo \$EXTERNAL_STORAGE"
def proc = cmd.execute()
println proc.in.text

任何人都可以告诉我发生了什么?真烦人......

-----------更新-------------------

我试过@JBirdVegas的代码,它似乎是由Android Studio 2.2.3版稳定引起的。我也试过

byte[] bytes = [47, 115, 116, 111, 114, 97, 103, 101, 47, 101, 109, 117, 108, 97, 116, 101, 100, 47, 108, 101, 103, 97, 99, 121, 13, 10]
println new String(bytes)

并且仍然和以前一样。

与命令行中的输出不同,当您在这些IDE的gradle面板中触发gradle任务时,:

enter image description here

如果您选择UTF_8,US_ASCII或ISO_8859_1的字符集,您将看不到任何内容。

2 个答案:

答案 0 :(得分:0)

似乎对我有用,但我怀疑这是Charset的问题。

在我的Mac上使用模拟器,我看到以下

tasks.create('testAdb') {
    def cmd = "adb shell echo \$EXTERNAL_STORAGE"
    def proc = cmd.execute()
    print "cmd result: $proc.in.text"
    byte[] bytes = [47, 115, 116, 111, 114, 97, 103, 101, 47, 101, 109, 117, 108, 97, 116, 101, 100, 47, 108, 101, 103, 97, 99, 121, 13, 10]
    print "new String bytes (with default charset): ${new String(bytes, Charset.defaultCharset())}"
    println "default charset: ${Charset.defaultCharset()}"
    print "new String bytes: ${new String(bytes)}"
    print "new String bytes (with UTF-8 charset): ${new String(bytes, StandardCharsets.UTF_8)}"
    println "new String bytes (with UTF-16 charset): ${new String(bytes, StandardCharsets.UTF_16)}"
    println "new String bytes (with UTF-16BE charset): ${new String(bytes, StandardCharsets.UTF_16BE)}"
    println "new String bytes (with UTF-16LE charset): ${new String(bytes, StandardCharsets.UTF_16LE)}"
    print "new String bytes (with US_ASCII charset): ${new String(bytes, StandardCharsets.US_ASCII)}"
    print "new String bytes (with ISO_8859_1 charset): ${new String(bytes, StandardCharsets.ISO_8859_1)}"
}


$ ./gradlew testAdb -q
cmd result: /sdcard
new String bytes (with default charset): /storage/emulated/legacy
default charset: UTF-8
new String bytes: /storage/emulated/legacy
new String bytes (with UTF-8 charset): /storage/emulated/legacy
new String bytes (with UTF-16 charset): ⽳瑯牡来⽥浵污瑥搯汥条捹ഊ
new String bytes (with UTF-16BE charset): ⽳瑯牡来⽥浵污瑥搯汥条捹ഊ
new String bytes (with UTF-16LE charset): 猯潴慲敧支畭慬整⽤敬慧祣਍
new String bytes (with US_ASCII charset): /storage/emulated/legacy
new String bytes (with ISO_8859_1 charset): /storage/emulated/legacy

答案 1 :(得分:0)

好的,最后我发现这些字节包含一个&#39; \ r&#39;(13),当打印到控制台时,整行的内容被清除,因此什么也看不见。< / p>