从csv文件读取数据 - 有效源的文件未找到异常

时间:2016-07-31 09:49:04

标签: java csv

我在从网络上读取csv文件时遇到问题。我收到了一个File not found异常。这是来源:http://data.okfn.org/data/core/s-and-p-500-companies/r/constituents.csv 如果我可以轻松打开它,怎么可能找不到该文件?我在这里错过了什么?

package Investing;


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

public class Main {

   public static void main(String[] args) {

    String csvFile = "http://data.okfn.org/data/core/s-and-p-500-     companies/r/constituents.csv";
    String line = "";
    String cvsSplitBy = ",";


    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] data = line.split(cvsSplitBy);

            System.out.println(data);

        }

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


}
}

1 个答案:

答案 0 :(得分:1)

FileReader用于本地文件。 有关读取远程cvs文件的信息,请参阅:Read remote .csv file using opencsv

另一种读取远程文件的方法:

public static void main(String[] args) {

    String csvFile = "http://data.okfn.org/data/core/s-and-p-500-companies/r/constituents.csv";

    try {
        URL url12 = new URL(csvFile);
        URLConnection urlConn = url12.openConnection();
        InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
        BufferedReader buff = new BufferedReader(inStream);

        String line = buff.readLine();
        line  = buff.readLine();
        while (line != null) {

            System.out.println(line);
            line = buff.readLine();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}