[英]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.