1

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

1
  • show us what you got !!! Commented Nov 22, 2009 at 23:00

4 Answers 4

3

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Now you have a trailing space.
Yes. Im shielding from that with my "pseudocode" comment. But ok, i'll add that in.
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.
3

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(" ");
    }
}

2 Comments

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.
I also don't know, but that's just a trivial change. I've added it.
1

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());

Comments

0

"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 );
       }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.