我正在尝试在Weka中读取。arff文件。我写了这段代码。我总是出错,对我的工作不确定。
public String fileArff(String filePath) throws Exception
{
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
ArffReader re = new ArffReader(br);
Instances data = re.getData();
data.setClassIndex(data.numAttributes()-1);
File file = new File(filePath);
if (file.exists() && file.isFile() && file.canRead()) {
return "The file exists";
}
while (data != null)
{
re.appened(data);
re.appened("n");
data = br.getData();
}
return re.toString();
}
catch (IOException e)
{
return "There is an error";
}
}
我正在尝试读取java语言的。arff文件,我使用了Weka库。
行data.setClassIndex
之后的代码要么是不必要的,要么是无效的(如re.appened
或br.getData
)。我建议阅读Weka API的Javadoc文档,以获取您想要使用的相关类。
下面的代码具有readArff
方法,该方法使用DataSource类(该类可以根据文件的扩展名自动使用Weka Loader)读取ARFF文件,并返回从中生成的Instances
数据集对象。如果文件不存在,它将抛出IOException
。
main
方法调用readArff
方法,期望在执行ArffHelper
类时提供一个参数(要读取的ARFF文件的路径)。
import weka.core.Instances;
import weka.core.converters.ConverterUtils;
import java.io.File;
import java.io.IOException;
public class ArffHelper {
public Instances readArff(String path) throws Exception {
if (!new File(path).exists())
throw new IOException("File does not exist: " + path);
Instances data = ConverterUtils.DataSource.read(path);
data.setClassIndex(data.numAttributes() - 1); // assuming that the class is the last attribute
return data;
}
public static void main(String[] args) throws Exception {
ArffHelper b = new ArffHelper();
Instances data = b.readArff(args[0]);
System.out.println(data);
}
}