简体   繁体   中英

Cannot read data from file

I am trying to read values from CSV file which is present in package com.example. But when i run code with the following syntax:

DataModel model = new FileDataModel(new File("Dataset.csv"));

It says:

java.io.FileNotFoundException:Dataset.csv

I have also tried using:

DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));

Still not working. Any help would be helpful. Thanks.

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

}

CSV file which is present in package com.example

You can use getResource() or getResourceAsStream() to access the resource from within the package. For example

InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader

(note exception handling and file closing are omitted above for brevity)

If this is the FileDataModel from org.apache.mahout.cf.taste.impl.model.file then it can't take an input stream and needs just a file. The problem is you can't assume the file is available to you that easily (see answer to this question ).

It might be better to read the contents of the file and save it to a temp file, then pass that temp file to 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));
...

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