从文件读入数组

时间:2017-11-08 15:56:05

标签: java arrays file

我完全难以尝试从文件中读取并将其添加到数组中。所以我试图实现的是将行读入一个临时的String数组,然后将临时值添加到主数组中,

这是我想逐行拆分成一个数组的文本文件的内容。这样我就可以占用每一行,用数字进行计算并格式化输出。

    Mildred Bush 45 65 45 67 65 into [[Mildred Bush],[45],[65],[67],[65]]
    Fred Snooks 23 43 54 23 76               etc.
    Morvern Callar 65 45 34 87 76            etc.
    Colin Powell 34 54 99 67 87
    Tony Blair 67 76 54 22 12
    Peter Gregor 99 99 99 99 99

然而,当主阵列中的运行是什么时候[Mildred,Fred,Morvern,Colin,Tony,Peter]。所以意味着只有第一个值被附加到主数组,并且我不确定如何在我的代码中将其修复为我需要的内容。

//要打开的文件的名称。

    String fileName = "Details.txt";

    String wfilename = "output.txt";

    // This will reference one line at a time
    String line = null;

    String temp;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        FileWriter fileWriter = new FileWriter(wfilename);


        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        List<String> parts = new ArrayList<>();
        String [] temp2;

        while((line = bufferedReader.readLine()) != null) {
            //System.out.println(line);
            temp = line;
            temp2 = line.split(" ");

            parts.add(temp2[0]);
            //System.out.println(line);
            bufferedWriter.write(line + "\n");
        }   
        System.out.print(parts);

        // Always close files.
        bufferedReader.close();   
        bufferedWriter.close();
    }
    catch(FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");                  

    }

更新尝试:

我发现原因是

    parts.add(temp2[0]);

但是当我尝试

    parts.add(temp2)

我遇到了错误

    The method add(String) in the type List<String> is not applicable for the arguments (String[])

所以基本上我正在努力的是在数组中添加一个数组。

EDIT2:

我试过

 for(int i=0; i<7; i++){
                parts.add(temp2[i]);
           }

,它将文件中的所有项目添加到一个数组中。我想知道是否有任何方法可以每7个术语拆分列表使其成为2D数组?

这不是必需的,但我觉得在进行计算时,使用for循环并在为每一行进行计算时执行[i + 7]是不好的做法。

2 个答案:

答案 0 :(得分:0)

试试这个:

           try{
                br = new BufferedReader(new FileReader("myfile.txt"));

                //Save line by line the file in ArrayList
                while( ( contentLine = br.readLine() ) != null ){               
                    arrlist.add(contentLine);
                }

                //Iterate the list and applies Split to get the data
                for(int i = 0; i < arrlist.size(); i++){
                    String[] splitString = arrlist.get(i).split(" ");
                        for(int j = 0; j < splitString.length; j++){
                            if(isNumeric(splitString[j])){
                                System.out.print(splitString[j]+"*");
                            }
                        }
                        System.out.println();
                }

            }catch(IOException io){
                io.printStackTrace();
            }

以下是方法isNumeric:

       public static boolean isNumeric(String str){  
          try{  
            double d = Double.parseDouble(str);  
          }  
          catch(NumberFormatException nfe){  
            return false;  
          }  
          return true;  
        }

我希望我帮助过......

答案 1 :(得分:0)

我遇到了类似的问题,我找到了一个多维数组的解决方案:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Test {

    //first I read the file into a String
    static String readFile(String fileName) throws IOException {
        BufferedReader br;
            br = new BufferedReader(new FileReader(fileName));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
                }
            return sb.toString();
        } finally {
            br.close();
        }
    }

    public static void main (String [] args) {
        String input = new String();
        try {
            input = readFile("Example.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Then I convert it
        String dimension1 = "\\|", dimension2 = " ", dimension3 = ","; //That could also be other characters

        String [] arrayString1D = input.split(dimension1);
        String [][] arrayString2D = new String[arrayString1D.length][];
        String [][][] arrayString3D = new String[arrayString2D.length][][];

        for(int x = 0; x < arrayString1D.length; x++) {
            arrayString2D[x] = arrayString1D[x].split(dimension2);
            arrayString3D[x] = new String [arrayString2D[x].length][];

            for(int y = 0; y < arrayString2D[x].length; y++) {
                arrayString3D[x][y] = arrayString2D[x][y].split(dimension3);
            }
        }

    //And here I print it out!
    System.out.println(Arrays.deepToString(arrayString3D));
    }
}

txt中的文字。文件可以是这样的:
word1,word2,word3,word4,word5|word6,word7 word8|word9,word10,word11 word12,word13

它会打印出来:
[[[word1, word2, word3, word4, word5]], [[word6, word7], [word8]], [[word9, word10, word11], [word12, word13]]]

我希望有所帮助! : - )