Search code examples
javastringmultiple-columnsfilewriterwriter

Writing columns into a text file


Before tagging my question as a duplicate question, please let me explain first!

I know using String.format will let the text to be written into two columns, but that is not what I need. Because using String.format just gives specified number of spaces between any two desirable strings. What I am looking is that if in the text file, we press tab key in Windows based systems, it jumps directly to the next column, or in other words, if we copy the content of the text file and paste it into some software like Excel, SPSS etc, it automatically pastes each column from text file into a separate column in the corresponding software. Here is my current code which does not satisfy my need:

String formatStr = "%20s %20s";
String query="some string";
int value="some int";
fop.write(String.format(formatStr,query,value));
fop.write(System.getProperty("line.separator"));
fop.flush();

Solution

  • You want tab separated values:

    String.format("%s\t%s", query, value);
    

    \t is the escape code for the "tab" character.