Java 无法从文件中读取数据

Java 无法从文件中读取数据,java,file,Java,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")); 仍然不起作用。 任何帮助

我试图从包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"));
仍然不起作用。 任何帮助都会有帮助。 谢谢

存在于包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


它不是一个类,所以它实际上不在包中。它是文件系统中的文件,还是jar文件中的文件?关于文件在如何运行代码的上下文中的位置,我们没有足够的信息。存在于包com.example在当前类上使用getClass.getResource或getClass.getResourceAsStream,传递包和资源名称例如/com/example/Dataset.csv.Hi非常感谢。我是专门找收银员的。您能告诉我Windows.np中tempFilePath的路径应该是什么吗。基本上,临时位置可以是应用程序具有读/写权限的任何内容。但很好地解释了默认的临时位置。因此,对于windows,它通常基于环境变量TEMP或java property System.getPropertyjava.io.tmpdir,但这可能因许多情况而有所不同。
InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader
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));
...