BALTIMORE—A former National Security Agency contractor accused of amassing at least 500 million pages of government records, including top-secret information on military operations, will remain in custody while awaiting trial, a judge ordered Friday.

Federal Magistrate Judge A. David Copperthite ruled during a hearing at the federal courthouse here that Harold “Hal” Martin III, of Glen Burnie, Md., met conditions for continuing detention. “I find by a preponderance of the evidence that the defendant does pose a risk of flight,”...