简体   繁体   中英

read .arff file using Weka library in java

I am trying to read an.arff file in Weka. I did this code. I keep getting error not sure about my work.

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";
        }
    }

I am trying to read a.arff file in java language, and I used Weka library.

The code after the line data.setClassIndex is either unnecessary or not valid (like re.appened or br.getData ). I recommend reading the Javadoc documentation of the Weka API for the relevant classes that you want to use.

The following code has the method readArff , which reads an ARFF file using the DataSource class (this class can the Weka Loader to use automatically based on the file's extension) and returns the Instances dataset object that it generated from it. It will throw an IOException if the file does not exist.

The main method calls the readArff method, expecting one argument (the path to the ARFF file to read) to be supplied when executing the ArffHelper class.

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM