2012-04-26 2 views
1

중요한 경로 방법을 사용하여 중요한 경로를 계산하려고합니다. 필자는 몇 가지 테스트 케이스를 가지고 있으며 출력은 "tarea2.out"파일에 출력되어야한다.Java로 텍스트 파일에 테스트 케이스의 출력을 오버라이드

문제는 파일을 인쇄 할 때 각 사례의 출력을 덮어 쓰고 결국 출력이 나에게 마지막으로 표시된다는 것입니다. 나는 바보 알고,하지만 난 자바에 새로운 그리고 난 출력이 올 수 없습니다

여기 내 코드입니다 :

package tarea; 

import java.io.*; 
import java.util.Arrays; 
import java.util.StringTokenizer; 

/** 
* 
* @author Francisco 
*/ 
public class Main { 
    public static int c; 

    public static void recorrido(int[][] adj) throws IOException{ 
     int n=adj.length; 
     int casitas[][] = new int[n][2]; 
     int mejorCamino[] = new int [n]; 

     int temp; 

     for(int i=0;i<n;i++){ 
      for(int j=0;j<n;j++){ 
       temp = adj[i][j]; 
       if(temp > -1){ 
        if(temp + casitas[i][0]>casitas[j][0]){ 
         casitas[j][0] = temp + casitas[i][0]; 
         mejorCamino[j] = i; 
        } 
       } 
      } 
     } 
     //Hacemos el paso hacia atrás. 
     for(int y=0;y<n;y++) 
     casitas[y][1] = casitas[n-1][0]; 

     for (int j=n-1;j>=0;j--){ 
      for(int i=0;i<n;i++){ 
       temp = adj[i][j]; 
       if(temp > -1){ 
        casitas[i][1]= Math.min(casitas[j][1] - temp , casitas[i][1]); 
       } 
      } 
     } 

     int x=n-1; 
     String cam = ""; 
     while(x>0){ 
      if(x==n-1) 
       cam= mejorCamino[x] + " " + x; 
      else 
       cam= mejorCamino[x] + " " + x + "\n" + cam; 
      adj[mejorCamino[x]][x] = -1; 
      x = mejorCamino[x]; 

     } 

     //Calculamos las holguras con nuestra nueva matriz 
     String mac=""; 
     int HT , HL; 
     for(int i=0;i<n;i++){ 
      for(int j=0;j<n;j++){ 
       temp = adj[i][j]; 
       if (temp > -1){ 
        HT = casitas[j][1] - temp - casitas[i][0]; 
        HL = casitas[j][0] - temp - casitas[i][0]; 
        mac += "\n" + i + " " + j + " " + HT + " " + HL; 
        if (HT>HL) 
         mac += " R"; 
       } 
      } 
     } 

     String sFichero = "tarea2.out"; 
     File fichero = new File(sFichero); 

     BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero)); 

     bw.write("Case " + c + ": total duration " + casitas[n-1][0]); 
       bw.write("\n"); 
       bw.write(cam); 
       bw.write(mac); 
       bw.write("\n"); 

       // Hay que cerrar el fichero 
     bw.close(); 
    } 


} 

답변

4

당신은 recorrido 방법을 호출 BufferedWriter의 모든 시간을 만들고 있습니다.

BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero)); 

파일은 매번 다시 작성됩니다. 모든 응용 프로그램에서 파일을 한 번 열고 recorrido 단지 대신에 내용을 작성하는 경우 더 나은 것, 그것은

BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero, true)); 

또한 추가 모드에서 파일을 열 것으로 알려 생성자에 true 매개 변수를 추가 여러 번 파일을 열거 나 닫습니다.

관련 문제