我正试图从CSV文件中读取值,该文件存在于包com.example中。但是当我用以下语法运行代码时:
DataModel model = new FileDataModel(new File("Dataset.csv"));
上面写着:
java.io.FileNotFoundException: Dataset.csv
我也试过使用:
DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));
仍然不能工作。任何帮助都会很有帮助。谢谢。
如果这是来自org.apache.mahout.cf.taste.impl.model.file
的FileDataModel
,那么它不能接受输入流,只需要一个文件。问题是你不能假设这个文件对你来说是那么容易的(见这个问题的答案)。
最好读取文件的内容并将其保存到临时文件中,然后将该临时文件传递给FileDataModel
。
InputStream initStream = getClass().getClasLoader().getResourceAsStream("Dataset.csv");
//simplistic approach is to put all the contents of the file stream into memory at once
// but it would be smarter to buffer and do it in chunks
byte[] buffer = new byte[initStream.available()];
initStream.read(buffer);
//now save the file contents in memory to a temporary file on the disk
//choose your own temporary location - this one is typical for linux
String tempFilePath = "/tmp/Dataset.csv";
File tempFile = new File(tempFilePath);
OutputStream outStream = new FileOutputStream(tempFile);
outStream.write(buffer);
DataModel model = new FileDataModel(new File(tempFilePath));
...
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
public void run() {
String csvFile = "file path of csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// Do stuff here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
CSV文件,存在于包com.example
您可以使用getResource()
或getResourceAsStream()
从包内访问资源。例如
InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader
(注意为简洁,上面省略了异常处理和文件关闭)