Squatters occupying a complex of abandoned buildings in Rio de Janeiro clashed with police Friday after a court ruling that allowed the premises to be cleared.

Hundreds of police moved into the area early in the morning, and Brazilian media reported that most of the 5,000 squatters left peacefully. But fighting soon broke out when some of the residents began throwing rocks at the police, who responded by firing rubber bullets, tear gas and percussion grenades.

One of the buildings, a truck, buses and police vehicles were set on fire, and local media reported that three bank branches were vandalized as the violence spread. Seven civilians and nine police officers were injured, a police spokesman said.

Squatters began taking over the complex, owned by a cellphone company, on March 31. The area came to be known as the Telerj Favela, or the slum of Telerj, the name of a telephone company that previously occupied the site, as more people moved in and also began living in improvised shelters on the premises.

Television showed images of demonstrators shouting, “We want houses,” but police said the situation was calm by afternoon.

Occupations of land and abandoned buildings are common in Brazil, where 11 million people live in favela-type communities, according to government figures. The problem is particularly acute in Rio de Janeiro, where 22 percent of the city’s 6.3 million residents live in favelas, according to the 2010 census.

For decades, armed drug gangs have dominated these areas, which often have economic and organizational structures apart from the rest of Brazilian society. The Telerj Favela was the most recent established in Rio.

As part of a program to quell the violence, 37 armed police bases have been established in favelas since 2008 in the run-up to the soccer World Cup this summer and the 2016 Summer Olympics. Some favelas have also been cleared to make way for works related to the events.

But the program has begun to show cracks as drug gangs thought to have been expelled have begun to fight back and gunfights have shaken previously pacified areas. The police have repeatedly been accused of human rights abuses, including torture and murder.

A Rio court approved the action in the Telerj Favela on April 4, a court spokesman said. “It is a judicial decision, given to the owner of the land, to retake possession of the land which was invaded,” he said.