+ Start a Discussion
Stuart FlemingStuart Fleming 

How to define a File object and read it in Apex

I am creating apex classes that will query our prod instance for sample data.  It will create a file or a static resource.    Then when I create the sandbox, I run a apex script that reads the file and uploads the data into the sandbox objects.
For example, the following show how to upload files using a visualforce page -- but I need to know how to define the File in Apex then read it.

https://reddymallareddy.blogspot.com/2017/08/read-and-insert-records-from-csv-file.html
http://sfdcsrini.blogspot.com/2014/04/how-to-read-csv-file-from-apex_17.html

I want to have code that basically does the following:

File xyz = 'accountData.txt' ;
csvFileLines = new String[]{};
acclist = New List<Account>(); 

String csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n'); 

            for(Integer i=1; i < csvFileLines.size(); i++){
                    Account acct = new Account();
                    string[] csvRecordData = csvFileLines[i].split(',');
                    acct.name = csvRecordData[0] ;             
                    acct.accountnumber = csvRecordData[1];
                    acct.Type = csvRecordData[2];
                    acct.AccountSource = csvRecordData[3];   
                    acct.Industry = csvRecordData[4];                                                                             
                    acclist.add(acct); 
                }

Can anyone provide any real working, comprehensive code that 
1.  Creates the file or static resource 
2.  In another class reads that file or static resource and loads it into 

I have been searching all over the net for examples, but can't find anything that is 100% apex.   Please do not just point me to the documentation (most of it is worthless) -- I need real code examples (that work), not just snippets of code.