SebastianFK
SebastianFK

Reputation: 7

I can't load my file?

i'm trying to cast a line in this code to String, but somehow it wont work.. The code wont even open the file. Here's the code:

package javagame;

import java.io.*;
import java.util.*;

import org.newdawn.slick.*;
import org.newdawn.slick.state.*;

public class Terrain {

    public static String test;

    private Scanner x;

    private final File world = new File("World.txt");

    public void openFile(){
        try{
            x = new Scanner(world);
        } catch (Exception e){
            System.out.println("Coudn't load ''World.txt''");
        }
    }

    public void readFile(){
        try{
            test = x.toString();
        } catch (Exception e){
            System.out.println("Couldn't cast to string");
        }
        System.out.println(test);
    }

    public void closeFile(){
        try{
            x.close();
        } catch (Exception e){
            System.out.println("Couldn't close file");
        }
    }
}

When i run the code i get these error messages: Coudn't load ''World.txt'' Couldn't cast to string null Couldn't close file

The file is located the same place as the other files in the main package.

Upvotes: 0

Views: 513

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

The most likely situation is that you are not running the program from the same location as the file you are trying to load. Try using a full path name to the file, or make sure that you run your program in the same directory that the file is located.

In a more complete program, you might specify the file that you want to read as a command line argument or as a system property.

Upvotes: 1

Related Questions