views:

736

answers:

4

Hi,

I'm trying to write a matrix into a text file. In order to do that I'd like to know how to write an array into a line in the text file.

I'll give an example:

int [] array = {1 2 3 4};

I want to have this array in text file in the format:

1 2 3 4

and not in the format:

1
2
3
4

Can you help me with that?

Thanks a lot

+2  A: 

Then don't write a new line after each item, but a space. I.e. don't use writeln() or println(), but just write() or print().

Maybe code snippets are more valuable, so here is a basic example:

for (int i : array) {
    out.print(i + " ");
}

Edit: if you don't want trailing spaces for some reasons, here's another approach:

for (int i = 0; i < array.length;) {
    out.print(array[i]);
    if (++i < array.length) {
        out.print(" ");
    }
}
BalusC
This leaves a trailing space at the end of the line. That might be suitable for the submitter, or it might not. I don't know.
Mark Byers
I also don't know, but that's just a trivial change. I've added it.
BalusC
+3  A: 

Here is a naive approach

//pseudocode
String line;
StringBuilder toFile = new StringBuilder();
int i=0;
for (;array.length>0 && i<array.length-2;i++){
   toFile.append("%d ",array[i]);
}

toFile.append("%d",array[i]);

fileOut.write(toFile.toString());
Tom
You forgot the spaces.
Mark Byers
Now you have a trailing space.
Mark Byers
Yes. Im shielding from that with my "pseudocode" comment. But ok, i'll add that in.
Tom
Now it fails with an exception if the array is empty. That might be suitable for the submitter, or it might not. I don't know.
Mark Byers
A: 

"Pseudocode"

for( int i = 0 ; i < array.lenght ; i++ )
    {
       if( i + 1 != array.lenght )
       {
          // Not last element
          out.write( i + " " );
       }
       else
       {
          // Last element
          out.write( i );
       }
    }
Ismael
+1  A: 

Ok, I know Tom already provided an accepted answer - but this is another way of doing it (I think it looks better, but that's maybe just me):

int[] content     = new int[4] {1, 2, 3, 4};
StringBuilder toFile = new StringBuilder();

for(int chunk : content) {
    toFile.append(chunk).append(" ");
}

fileOut.write(toFile.toString().trim());
Björn