Problème d'E/S de fichier de texte Java


Je dois faire un jeu de torpille pour l'école avec une toplist pour cela. Je veux le stocker dans une structure de dossiers près du POT: /Torpedo/local/toplist/top_i.dat, où le i est l'endroit de ce score. Les fichiers seront créés au premier démarrage du programme avec cet appel:

File f;
f = new File(Toplist.toplistPath+"/top_1.dat");
if(!f.exists()){

        Toplist.makeToplist();
}

Voici la classe toplist:

package main;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.prefs.Preferences;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class Toplist {

static String toplistPath = "./Torpedo/local/toplist"; //I know it won't work this easily, it's only to get you the idea

public static JFrame toplistWindow = new JFrame("Torpedó - [TOPLISTA]");
public static JTextArea toplist = new JTextArea("");

static StringBuffer toplistData = new StringBuffer(3000);

public Toplist() {
    toplistWindow.setSize(500, 400);
    toplistWindow.setLocationRelativeTo(null);
    toplistWindow.setResizable(false);

    getToplist();

    toplist.setSize(400, 400);
    toplist.setLocation(0, 100);
    toplist.setColumns(5);
    toplist.setText(toplistData.toString());
    toplist.setEditable(false);
    toplist.setBackground(Color.WHITE);


    toplistWindow.setLayout(null);
    toplistWindow.setVisible(true);
}

public Toplist(Player winner) {

    //this is to be done yet, this will set the toplist at first and then display it

    toplistWindow.setLayout(null);
    toplistWindow.setVisible(true);
}

/**
 * Creates a new toplist
 */
public static void makeToplist(){
    new File(toplistPath).mkdir();
    for(int i = 1; i <= 10; i++){
        File f = new File(toplistPath+"/top_"+i+".dat");
        try {
            f.createNewFile();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista létrehozása", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}


/**
 * If the score is a top score it inserts it into the list
 * 
 * @param score - the score to be checked
 */
public static void setToplist(int score, Player winner){
    BufferedReader input = null;
    PrintWriter output = null;

    int topscore;

    for(int i = 1; i <= 10; i++){
        try {
            input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+",dat"));
            String s;
            topscore = Integer.parseInt(input.readLine());
            if(score > topscore){
                for(int j = 9; j >= i; j--){
                    input = new BufferedReader(new FileReader(toplistPath+"/top_"+j+".dat"));
                    output = new PrintWriter(new FileWriter(toplistPath+"/top_"+(j+1)+".dat"));
                    while ((s = input.readLine()) != null) {
                        output.println(s);
                    }
                }
                output = new PrintWriter(new FileWriter(toplistPath+"/top_"+i+".dat"));
                output.println(score);
                output.println(winner.name);
                if(winner.isLocal){
                    output.println(Torpedo.session.remote.name);
                }else{
                    output.println(Torpedo.session.remote.name);
                }
                output.println(Torpedo.session.mapName);
                output.println(DateUtils.now());
                break;
            }


        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
            if (output != null) {
                output.close();
            }
        }
    }



}

    /**
      * This loads the toplist into the buffer
      */
public static void getToplist(){
    BufferedReader input = null;
    toplistData = null;
    String s;

    for(int i = 1; i <= 10; i++){
        try {
            input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+".dat"));
            while((s = input.readLine()) != null){
                toplistData.append(s);
                toplistData.append('\t');
            }
            toplistData.append('\n');
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

/**
 * 
 * @author http://www.rgagnon.com/javadetails/java-0106.html
 *
 */
public static class DateUtils {
      public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

      public static String now() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(cal.getTime());

      }
    }

}

Le problème est qu'il ne peut accéder à aucun des fichiers. J'ai essayé de les ajouter au classpath et au moins six variantes différentes de la gestion des fichiers/chemins trouvé en ligne, mais rien n'a fonctionné. Quelqu'un pourrait-il me dire ce que je fais de mal?

Merci.

Author: NG., 2010-04-18

1 answers

Lorsque vous traitez des fichiers, le chemin est relatif à l'endroit où vous exécutez l'application. Lors de son exécution à partir d'eclipse, le chemin de base est le dossier du projet.

Ce que vous feriez normalement si le fichier n'existe pas, c'est appeler mkdirs() sur le parent pour créer la hiérarchie des dossiers, puis créer le fichier.

 1
Author: Guillaume, 2010-04-18 16:44:27