【问题标题】:Reading from files into an array从文件读入数组
【发布时间】:2017-11-08 15:56:05
【问题描述】:

我在尝试从文件中读取并将其添加到数组时完全被难住了。所以我尝试实现的是将该行读入一个临时字符串数组,然后将临时值添加到主数组中,

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

    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[])

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

编辑2:

我试过了

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

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

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

【问题讨论】:

  • 您是否尝试使用debugger 单步执行该代码?
  • 看看doc 很确定你会发现一些允许你在前几个方法中将数组添加到数组中的东西;)
  • 您的拆分有问题。它也会拆分这两个词,所以 [0] 只返回第一个词。 “Mildred Bush”只会给你“Mildred”,这可能不是你想要的

标签: java arrays file


【解决方案1】:

试试这个:

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

希望我能帮到你……

【讨论】:

    【解决方案2】:

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

    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]]]

    希望对您有所帮助! :-)

    【讨论】:

      猜你喜欢
      • 2014-05-04
      • 2013-03-29
      • 1970-01-01
      • 2013-12-14
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多