We consider a real massless scalar field inside a cavity with a moving mirror in a two-dimensional spacetime, satisfying the Dirichlet or Neumann boundary condition at the instantaneous position of the boundaries, for an arbitrary and relativistic law of motion. Considering an arbitrary initial field state, we show that the exact value of the energy density in the cavity can be obtained by tracing back a sequence of null lines, connecting the value of the energy density at the given spacetime point to a certain known value of the energy density at a point in the region where the initial field modes are not affected by the boundary motion. We obtain the particular formulas for the energy density of the field and the quantum force acting on the boundaries for a vacuum, thermal, and a coherent state. We thus generalize a previous result in literature [17], where this problem is approached for only one mirror. For the particular cases of vacuum and Dirichlet boundary condition, nonrelativistic velocities, or in the limit of large length of the cavity, our results coincide with those found in the literature.