The solvent exchange procedure has become the most-used protocol to produce surface nanobubbles, while the molecular mechanisms behind the solvent exchange are far from being fully understood. In this paper, we build a simple model and use molecular dynamics simulations to investigate the dynamic characteristics of solvent exchange for producing nanobubbles. We find that at the first stage of solvent exchange, there exists an interface between interchanging solvents of different gas solubility. This interface moves toward the substrate gradually as the exchange process proceeds. Our simulations reveal directed diffusion of gas molecules against the gas concentration gradient, driven by the solubility gradient of the liquid composition across the moving solvent-solvent interface. It is this directed diffusion that causes gas retention and produces a local gas oversaturation much higher near the substrate than far from it. At the second stage of solvent exchange, the high local gas oversaturation leads to bubble nucleation either on the solid surface or in the bulk solution, which is found to depend on the substrate hydrophobicity and the degree of local gas oversaturation. Our findings suggest that solvent exchange could be developed into a standard procedure to produce oversaturation and used to a variety of nucleation applications other than generating nanobubbles.