WeaponGod243
WeaponGod243

Reputation: 19

How to fix this 'java.io.FileNotFoundException'

My RPG is doing just fine in the compiler. It inputs a file and reads it with Scanner, but when I export it into a ".jar" file it throws the FileNotFoundException.

I have tried putting the file in different locations. I have tried using different ways to call up the file. Nothing seems to be working.

package worldStuff;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class World {

    public static String[][] initWorld(String[][]array,String name) throws FileNotFoundException {
        int j = 0;
        String string;
        Scanner input = new Scanner(new File(name+".map"));
        while(j!=30) {
            string = input.nextLine();
            array[j] = string.split(",");
            j++;
        }
        input.close();
        return array;
    }

}

That is the method for inputting the file. I need a way for it to not error after compiling. I am using the Eclipse IDE with the export on this configuration:Eclipse Configuraiton

Upvotes: 0

Views: 1453

Answers (1)

Ivan Tomić
Ivan Tomić

Reputation: 171

If you've got the option to use Java8, how about this:

public static void main( String[] args ) {
        try {
            String[][] output = initWorld( "E:\\Workspaces\\Production\\Test\\src\\test\\test" );
            for ( String[] o : output ) {
                if ( o == null || o.length == 0 ) { break; }
                System.out.println( "- " + o[0] );
            }
        } catch ( FileNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    public static String[][] initWorld( String name ) throws FileNotFoundException {

        String array[][] = new String[30][];
        try (Stream<String> stream = Files.lines(Paths.get(name))) {
            List<String> inputList = stream.collect(Collectors.toList());
            for ( int i = 0; i < 30 && i < inputList.size(); i++ ) {
                array[i] = inputList.get( i ).split( "," );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return array;
    }

the main method is jsut for testing purposes here (prints the first element of each initialized array).

Also, no need to pass String[][] as an argument.

Just replace the initWorld argument with whatever your path to the target file is (make sure to use \ if you're on windows, \ by itself is an escape character ).

Hope that helps.

Upvotes: 1

Related Questions