Java:将数组写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1780324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:33:43  来源:igfitidea点击:

Java: write an array into a text file

javaarraysfilematrix

提问by dedalo

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

int [] 数组 = {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

非常感谢

采纳答案by Tom

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

回答by BalusC

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

然后不要在每个项目后写一个新行,而是一个空格。即不使用writeln()or println(),而只使用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(" ");
    }
}

回答by Ismael

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

回答by Bj?rn

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