There are several reasons the water in the pipe stays relitvely uncontaminatexd
1) Given the water treatment plant filters, cleans, and treats the water to rigorous standards
2) The water is stored at high pressure. Once it leaves the facility it is pumped at high pressure 60 -120 psi to distribute through the water system. You have a regulator at your home which dials the pressure down to 60 psi or so. The high pressure reduces the chance of contaminants leeching in from the outside.
3) While in the pipes and under pressure the water is not exposed to air which contains bacteria and other bugs.
Before we got Town water on my road, my home used a well for our water. Once the Town water was hooked up I had to install check valves and separators to prevent any of my water from accidentally mixing with the Town water. The system is regularly inspected, at $90 per pop to make sure the system is working correctly.
I use well water to fill my fish pond and water the garden. I use Town water for cooking, drinking, bathing, etc.