0

I´m trying to open a csv file inside a android project. Inside the res folder I created a new folder named raw.

This is my code:

 public File readFromFile(){ 
        URL url = DemoReader.class.getResource("/res/raw/demosystemsoverview.csv");
        if (url == null) {
            throw new IllegalArgumentException("file is not found!");
        } else {
            File f = new File(url.getFile());
            if (f.exists()){
                return f;
            }else{
                throw new IllegalArgumentException("file does not exist!");
            }
        }
    }

I don´t get the file not found exception but I get the file does not exist exception. My goal is to use a bufferedReader but I think I have to solve this before.

Thriggle
  • 7,009
  • 2
  • 26
  • 37
Nonny
  • 1

1 Answers1

0

You can do something like this...

List<String> list = new ArrayList<>();
List<String> splittedString = new ArrayList<>();
StringBuffer buffer = new StringBuffer();
InputStream in = this.getResources().openRawResource(R.raw.yourFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
if (in !=null){
   try {
        while ((data = reader.readLine()) !=null){
        buffer.append(data+"\n");
        list.add(data);
        }
        gatheringData(list);
        in.close();
        }catch (Exception e){
         e.printStackTrace();
        }
 }

 private void gatheringData(List<String> list) {
    for (String s : list){
        splittedString = new ArrayList<>();
        splittedString = Arrays.asList(s.split(",[ ]*"));
        Log.d(TAG,splittedString[0]);
        Log.d(TAG,splittedString[1]);
    }
}

Depending upon the number of column(n)in your csv file.You can access it from splittedString indexes. splittedString[0]....splittedString[n] .

Hritik Gupta
  • 611
  • 5
  • 20
  • InputStream in = this.getResources().openRawResource(R.raw.yourFile); this does not work. (Cannot resolve method) I need to add context.getResources() but when I do this the app crashes. – Nonny Oct 16 '19 at 14:52
  • Try calling getResources() without the context. InputStream in =getResources().openRawResource(R.raw.yourFile); – Hritik Gupta Oct 17 '19 at 07:56