Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a tab character as a command line argument in Java [duplicate]

Tags:

java

bash

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

like image 503
bhaall Avatar asked Oct 31 '16 08:10

bhaall


People also ask

Is tab a character in Java?

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.

Can you use tab in Java?

Indentation: tabs vs spaces Java: 4 spaces, tabs must be set at 8 spaces. Both are acceptable.

How do you pass two command line arguments?

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.


2 Answers

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')"
like image 172
Costi Ciudatu Avatar answered Oct 14 '22 10:10

Costi Ciudatu


The simplest by far is:

java my.package.Main $'\t'
like image 25
alamar Avatar answered Oct 14 '22 09:10

alamar