2016-04-15 71 views
-4

我有一个看起来像43 78 63 73 99 ....的.txt文件,即 所有的值都由空格分隔。 我想把它们中的每一个都加入到一个数组中,这样 a[0]=43 a[1]='78 a[2]=63等等。 我该如何在Java中执行此操作..请解释将txt文件的内容存储在数组中

+0

纯粹的代码写入请求在堆栈溢出上偏离主题 - 我们期望 这里的问题与*特定的*编程问题有关 - 但我们 会很高兴地帮助您自己编写它!告诉我们 [你试过的东西](http://stackoverflow.com/help/how-to-ask),以及你卡在哪里。 这也将帮助我们更好地回答你的问题。 –

回答

0

将文件读入字符串。然后将空间中的字符串溢出到字符串数组中。

0

嗯,我会用文本文件存储到一个字符串做到这一点。 (只要它不太大)然后我会使用.split(“”)将它存储到一个数组中。

像这样:

String contents = "12 32 53 23 36 43"; 
//pretend this reads from file 

String[] a = contents.split(" "); 

现在阵 'A' 应该存储在其中的所有值。如果你想让数组成为一个int,你可以使用一个int数组,并使用Integer.toString()来转换数据类型。

0
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

public class readTextToIntArray { 
public static void main(String... args) throws IOException { 
    BufferedReader reader=new BufferedReader(new FileReader("/Users/GoForce5500/Documents/num.txt")); 
    String content; 
    List<String> contentList=new ArrayList<String>(); 
    while((content=reader.readLine())!=null){ 
     for(String column:content.split(" ")) { 
      contentList.add(column); 
     } 
    } 
    int[] result=new int[contentList.size()]; 
    for(int x=0;x<contentList.size();x++){ 
     result[x]=Integer.parseInt(contentList.get(x)); 
    } 
} 
} 

您可以使用它。

+0

帮助初学者时,通常最好提供解释,而不是只发布编译的代码。 – Signal

相关问题