开发者

Java: write an array into a text file

开发者 https://www.devze.com 2022-12-12 19:04 出处:网络
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'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 m开发者_Python百科e with that?

Thanks a lot


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


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消