Reputation: 678
I have a problem reading a csv file from the web. I get a File not found exception. That's the source: http://data.okfn.org/data/core/s-and-p-500-companies/r/constituents.csv How could it be the file cannot be found if I can easily open it ? what am I missing here ?
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();
}
}
}
Upvotes: 0
Views: 1673
Reputation: 18792
FileReader is used for local files. See: Read remote .csv file using opencsv for reading a remote cvs file.
Another alternative to read a remote file in:
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();
}
}
Upvotes: 1