Create Chatter Post With Attachment Using Apex

Sample Code:

//Upload File
ContentVersion cv = new ContentVersion();
cv.Title = 'Chatter Post Document';//File title
cv.PathOnClient = 'chattertestdoc.pdf';//File name
cv.VersionData = Blob.valueOf('Test Content');//File body (Add content or body of uploaded file)
cv.Description = 'Chatter Post Document';//File description
insert cv;

//Create Chatter Post
FeedItem fi = new FeedItem();
fi.Body = 'Chatter post from apex with attachment';
fi.ParentId = '0010I00002AbcMm'; //Record Id
insert fi;

//Associate attachment to the post
FeedAttachment fa = new FeedAttachment();
fa.FeedEntityId = fi.Id;//Chatter Post Id
fa.RecordId = cv.Id;//Document Id
fa.Type = 'CONTENT'; 
insert fa;