简体   繁体   中英

Java: write an array into a 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 me with that?

Thanks a lot

Then don't write a new line after each item, but a space. Ie 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(" ");
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM