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
Java Practices->Don't use tab characters. Most code editors allow you to use TAB characters in your source code. Such TAB characters will appear at the start of each line of your code, controlling indentation.
Indentation: tabs vs spaces Java: 4 spaces, tabs must be set at 8 spaces. Both are acceptable.
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative.
The tab
that you defined in code is a single-character string (since "\t" is an escape sequence).
From the command line you get a two-characters string, as bash doesn't handle "\t" as the tab character.
To pass that from command line, you can use echo -e
which supports escape sequences like \t
(or \n
and a few others):
$ java Main "$(echo -en '\t')"
The simplest by far is:
java my.package.Main $'\t'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With