【问题标题】:Using FileReader in a non-main method [closed]在非主要方法中使用 FileReader [关闭]
【发布时间】:2013-09-04 13:06:58
【问题描述】:

我可以使用下面的代码将 CSV 文件读入我的 Java ma​​in 方法。

我想要实现的是能够在 not 我的 ma​​in 方法中使用以下代码。我希望能够从我的 ma​​in 调用此方法,这样我就可以读取 CSV 文件,而不会让所有这些代码弄乱我的 ma​​in。我该怎么做?

仅供参考,CSV 文件有 2 列双精度,因此使用 double [][]

public static void main(String[] args) throws IOException {

    double [][] data = new double [100][2];    
    File file = new File("C:\\Users\\Username\\Java\\Test2\\First\\src\\Program1\\prac.csv");
    int row = 0;
    int col = 0;
    BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
    String line = null;


    //read each line of text file
    while((line = bufRdr.readLine()) != null && row < data.length) {
        StringTokenizer st = new StringTokenizer(line,",");
        while (st.hasMoreTokens()) {
            //get next token and store it in the array
            data[row][col] = Double.parseDouble(st.nextToken());
            col++;
        }
        col = 0;
        row++;
    }

}

【问题讨论】:

  • 我们通常要求您在来这里之前至少尝试解决问题,并解释这种尝试的含义。
  • 我认为void 不会返回任何值。
  • @ChrisBode 我是新手,所以我的尝试很愚蠢,会浪费大家的时间。

标签: java parsing csv methods main


【解决方案1】:

定义一个名为 CSVReader 的自定义类 -

public class CSVReader {

    public List<List<Double>> read (File file) throws IOException {
        List<List<Double>> data = new ArrayList<List<Double>>();    

        BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
        String line = null;

        //read each line of text file
        while((line = bufRdr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line,",");
            List<Double> row = new ArrayList<Double>();

            while (st.hasMoreTokens()) {
                //get next token and store it in the array
                row.add(Double.parseDouble(st.nextToken()));
            }

            data.add(row);
        }

        return(data);
    }
}

然后,主要 -

public static void main(String[] args) {
    List<List<Double>> data;
    String fileName = "C:\\Users\\Username\\Java\\Test2\\First\\src\\Program1\\prac.csv";
    File file = new File(fileName);

    try {
        CSVReader reader = new CSVReader();
        data = reader.read(file);
    }
    catch (IOException ex) {

        // handle your exception
    }
}

请注意,我使用Lists 而不是数组来读取数据。这比使用二维数组要干净得多——我不再需要执行任何绑定检查,也不必增加数组索引等。您可以阅读Effective Java,第 25 项 - 更喜欢列表而不是数组 - 了解更多好处。

【讨论】:

    【解决方案2】:

    只需将其移入新方法:

    public static double[][] readData(String fName){
        double [][] data = new double [100][2];    
        File file = new File(fname);
        int row = 0;
        int col = 0;
        BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
        String line = null;
    
    
        //read each line of text file
        while((line = bufRdr.readLine()) != null && row < data.length) {
            StringTokenizer st = new StringTokenizer(line,",");
            while (st.hasMoreTokens()) {
                //get next token and store it in the array
                data[row][col] = Double.parseDouble(st.nextToken());
                col++;
            }
            col = 0;
            row++;
        }
    
        return(data);
    }
    

    它是静态的,无需实例化类就可以从 main 调用。

    【讨论】:

      【解决方案3】:

      我相信你的代码很容易。您只需创建另一个名为 readCSV 的方法并返回数据,然后您可以在 main 方法中调用 readCSV。 readCSV 中的代码正是您现在在 main 方法中所做的。

      顺便说一句,我注意到您在阅读器完成工作后并没有关闭它,并且您尝试在 main 方法中返回一个值,而 main 的返回类型应该是 void,即什么都没有。

      【讨论】:

        【解决方案4】:

        试试这个:

        public static void main(String[] args) throws IOException {
            double[][] data = readFile("C:\\Users\\Username\\Java\\Test2\\First\\src\\Program1\\prac.csv");
        }
        
        public static double[][] readFile(String filepath) throws NumberFormatException, IOException {
            double[][] data = new double[100][2];
            File file = new File(
                    filepath);
            int row = 0;
            int col = 0;
            BufferedReader bufRdr = new BufferedReader(new FileReader(file));
            String line = null;
        
            // read each line of text file
            while ((line = bufRdr.readLine()) != null && row < data.length) {
                StringTokenizer st = new StringTokenizer(line, ",");
                while (st.hasMoreTokens()) {
                    // get next token and store it in the array
                    data[row][col] = Double.parseDouble(st.nextToken());
                    col++;
                }
                col = 0;
                row++;
            }
        
            return (data);
        }
        

        【讨论】:

          猜你喜欢
          • 2017-10-19
          • 2021-06-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-13
          • 2013-12-16
          • 1970-01-01
          • 2013-01-25
          相关资源
          最近更新 更多