views:

114

answers:

1

Hello,

I have to make a torpedo game for school with a toplist for it. I want to store it in a folder structure near the JAR: /Torpedo/local/toplist/top_i.dat, where the i is the place of that score. The files will be created at the first start of the program with this call:

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

        Toplist.makeToplist();
}

Here is the toplist class:

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());

      }
    }

}

The problem is, that it can't access any of the files. I've tried adding them to the classpath and at least six different variations of file/path handling I found online but nothing worked. Could anyone tell me what do I do wrong?

Thank you.

A: 

When you dealing with files, the path is relative to where you execute the application. When running it from eclipse, the base path is the project folder.

What you would normally do if the file doesn't exist is calling mkdirs() on the parent to create the folder hierarchy, then create the file.

Guillaume
I do that in the makeToplist()
KáGé
I regret to ask this, but please could anyone help me with a complete solution? I couldn't start with this program in time due to another class project and now I'm really running out of time and this is the only part missing.Thank you very much in advance.
KáGé
You're not using mkdirs(), you're using mkdir() which is a different method (see the javadoc). If it doesn't work, please show us the exception you get, it will be easier to help.
Guillaume
Oh I see.Mkdirs works, now the getToplist returns a nullpointer exception at line 156, thats the toplistData.append('\n');
KáGé
You might want to initialize it like this: toplistData = ""; instead of toplistData = null;
Guillaume
That returns a type mismatch error, cause it's not a string but a stringbuffer. But I've commented out the toplistData = null; lines and now the getToplist works, but the setToplist still doesn't
KáGé
I've figured it out...
KáGé