Create static resource with apex code

You will have to go with MetaData API. Something as below -

    MetadataService.MetadataPort service = createService();     
    MetadataService.StaticResource staticResource = new MetadataService.StaticResource();
    staticResource.fullName = 'MyResource';
    staticResource.contentType = 'text';
    staticResource.cacheControl = 'public';
    staticResource.content = EncodingUtil.base64Encode(Blob.valueOf('Static stuff'));
    MetadataService.AsyncResult[] results = service.create(new List<MetadataService.Metadata> { staticResource });

Remember that each create call corresponds to a callout. Here is a brilliant repository on Metadata API that can help you out.

https://github.com/financialforcedev/apex-mdapi