现在的位置: 首页 > 问答 > 正文

Passing a tab character as a command line argument in Java

2016年11月01日 问答 ⁄ 共 1156字 ⁄ 字号 暂无评论

So, basically, I want to successfully pass an arbitrary string in java that could contain special characters (such as tabs). Here's this code sample:

String tab = "\t"; 
//String tab = args[0];
String full = "hi"+tab+"hi"+tab+"bye";
String[] parts = full.split(tab);
String print = "";
for (String s : parts) {
    print += s + tab;
}
print = print.substring(0, print.length()-tab.length());
System.out.println(print);

Split successfully recovers the parts regardless of how the variable tab is defined. However, when it's actually printed, defining tab manually (the non-commented out version) prints it as expected, with tab characters. However, passing through command line causes it to actually print "\t" (the same as if the String was actually "\\t" for instance).

I'm primarily using bash, and would be happy for any bash-specific ideas, though would be happier if it also included a general explanation of what's happening. Why is the regex of both the same while the String literal is different?

bash invocation of the program:

ARGS="$X $Y $Z \t"

java -cp $CLASSPATH $MEM $PROGRAM $ARGS 2> "${PROGRAM##*.}-error.log" > "${PROGRAM##*.}-out.log"

The answer provided here does actually mostly work for my purposes, is fairly readable, and generally only fails on fairly unusual things: "\\\t", for instance: https://gist.github.com/uklimaschewski/6741769

给我留言

您必须 [ 登录 ] 才能发表留言!

×