A court ruled late Friday that California is obligated to return $331 million that it took from a fund designated to help troubled borrowers but instead used to plug holes in the state’s budget.

The ruling, by a state court judge in Sacramento, came in response to a lawsuit filed last year against Gov. Jerry Brown by three nonprofit groups offering counseling to homeowners. They contended that Mr. Brown improperly diverted some of the money California received in 2012 as part of a $25 billion nationwide settlement with the country’s largest banks over mortgage servicing improprieties.

The plaintiffs argued that $350 million of California’s share of the settlement was wrongly removed from a special fund dedicated to helping troubled homeowners avoid foreclosure through counseling and other educational services.

Judge Timothy M. Frawley agreed with the plaintiffs that $331 million of that was misused. In his ruling, he enjoined the state to return that amount to the special homeowner fund “as soon as there is sufficient appropriation ‘reasonably’ and ‘generally’ available for such purpose.”