java - 文本文件操作: Take data from text file and write a new text file with the data taken from the original file

标签 java sorting arraylist read-write

我正在编写一个程序来操作文本文件中的一些数据。我应该从包含比这 4 个信息更多的信息的文件中获取州 ID、人口、入学率和贫困率,并将它们写入一个新的文本文件。然后使用这个新的文本文件做一些数学运算。 这是原始文本文件结构:
This is the original text file structure 我在代码中遇到了错误,希望得到一些帮助。具体来说,错误是索引越界,并且无法从此上下文引用非静态方法。

定义要提取的数据的类:
Class to define data for extraction 完成实际提取的类:
Class where the actual extraction is done 公共(public)人口数据(字符串stateId,字符串totPopulation,字符串 schoolGoingPopuplation, 字符串 povertPopulation) { this.stateId = stateId; this.totPopulation = totPopulation; this.schoolGoingPopuplation = schoolGoingPopuplation; this.povertPopulation = povertPopulation; }

  public String getState()
  {
     return stateId;
  }

  public String getPopulation()
  {
     return totPopulation;
  }

  public String getSchool()
  {
     return schoolGoingPopuplation;
  }

  public String getPoverty()
  {
     return povertPopulation;
  }

  public String toString()
  {
     return this.stateId + " " + this.totPopulation + " " + 
     this.schoolGoingPopuplation + " " + this.povertPopulation;
  }   

//这是主类

         inFile = new InputStreamReader(new FileInputStream(inFileName));

        OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream(outFileName));

        while(scanner.hasNext()) {

           String line = scanner.nextLine();

           String[] columns = line.split(" ");

           String sateId = columns[0];

           String totPopulation = columns[9]; 

           String schoolGoingPopuplation = columns[10]; //index out of bounds occured

           String povertPopulation = columns[11]; //index out of bounds occured

           PopulationData pd = new PopulationData(sateId, totPopulation, schoolGoingPopuplation, povertPopulation);
           data.add(pd);

           outFile.write(pd.toString()); 
        } 
        for(PopulationData pd : data){ 
           System.out.println(pd.toString()); 
        }       
     }
     catch(IOException except)
     {
        except.printStackTrace();
     }
  }

最佳答案

第 28,30,32 行:文件中的字段是否真的由制表符分隔,并且恰好是一个制表符?看起来不像。我的猜测是它使用了空格,并且您的拆分生成了一个仅包含一列的数组,即整行。鉴于您有一个扫描仪实例,您可能打算使用它来通过 .nextInt().next() 方法读取字段。

第 37 行:.add() 方法返回一个 boolean 值,您正尝试将其写入流。您可能想写 outfile.write(pd.toString())

第 40 行:您可能指的是 System.out.println(pd.toString()),您所拥有的实际上是 PopulationDataManipulation.toString(),它不起作用,因为它是一个实例方法,而您的 main 是静态的。

关于java - 文本文件操作: Take data from text file and write a new text file with the data taken from the original file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769728/

相关文章:

java - 如何从 JTable 中获取鼠标选择的行

java - 如何在 Android Studio 中使用 FCM 和 Bazel?

algorithm - 对给定的成对排序进行排序

java - 将对象添加到 ArrayList 时遇到问题

java - 将 Java FX 表单数据添加到 ArrayList

java - 如何将一个应用程序中的内容与其他应用程序一起安装

java - 生产者/消费者死锁原因及调试

python - 创建基于散列的排序算法

c# - 你能提供数组排序的替代算法吗?

java - 从文件加载对象的ArrayList