Question

I have an object that I am writing to an output file.

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("output.txt"));        
            bufferedWriter.write("Id"+"\t"+"Symbol"+"\t"+ Arrays.toString(data.symbols));
            bufferedWriter.write("\n");
            for (int i = 0; i < data.cIds.length; i++) {
                bufferedWriter.write(data.ids[i]+"\t"+data.iSymbols[i]+"\t"
                        +Arrays.toString(data.matData[i])+"\n");

I get a table in the output file:

Id  Symbol  [001, 002, 003, 004, 005]
#1  a01 [2.3, 5.5, 4.5, 1.2, 3.3]
#2  a02 [2.2, 4.5, 7.5, 6.2, 9.3]

...and so on. How can I display the arrays without the brackets and as tab-separated strings, so that the output is like this:

Id  Symbol  001  002  003  004  005
#1   a01    2.3, 5.5, 4.5, 1.2  3.3
#2   a02    2.2  4.5  7.5  6.2  9.3
Was it helpful?

Solution

You can implement your own toString method that returns tab delimited string

something like

public static String toString(Object[] array)
{
  StringBuilder builder = new StringBuilder();


for(Object o: array)
  {
    builder.append(o+"\t");
  }
  return builder.toString().trim();

}

OTHER TIPS

Use this to replace '[ , ]' ,

Arrays.toString(data.matData[i]).replaceAll("[\\[ | \\]]", "")

Using Guava it looks as simple as this:

Double[][] data = {
        { 2.3, 5.5, 4.5, 1.2,  3.3 },
        { 2.2,  4.5,  7.5,  6.2,  9.3 }};

for (int row=0; row<data.length; row++) {
    System.out.println(Joiner.on("\t").join(data[row]));
}

You do not need Guava. You may do it as well using a loop and a StringBuilder:

Double[][] data = {
        { 2.3, 5.5, 4.5, 1.2,  3.3 },
        { 2.2,  4.5,  7.5,  6.2,  9.3 }};

for (int row=0; row<data.length; row++) {
    StringBuilder builder = new StringBuilder();
    String prefix = "";
    for (int col=0; col<data[row].length; col++) {
        builder.append(prefix).append(data[row][col]);
        prefix = "\t";
    }
    System.out.println(builder);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top