[英]Cannot read data from file
我正在尝试从com.example软件包中的CSV文件读取值。 但是当我使用以下语法运行代码时:
DataModel model = new FileDataModel(new File("Dataset.csv"));
它说:
java.io.FileNotFoundException:Dataset.csv
我也尝试过使用:
DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));
还是行不通。 任何帮助都会有所帮助。 谢谢。
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");
}
}
包com.example中存在的CSV文件
您可以使用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
(请注意,为简洁起见,上面省略了异常处理和文件关闭)
如果这是来自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));
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.