문제

I'm working on a project for my class and we are supposed to read in a file called sampleSearch.txt included below is the code that I'm working with. The problem is that through eclipse I can't seem to be able to actually load the file in. It always comes up with File Not Found even though the text file is in the same directory as the rest of the code.

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

   public class Driver{    
   public static void main (String[] args){
    // try block needed to read in file
    try
    {
        //open the file "sampleSearch.txt"
        FileReader fileName = new FileReader("sampleSearch.txt");
        Scanner fileRead = new Scanner(fileName);

        //read in the number of rows
        int numRow = fileRead.nextInt();
        fileRead.nextLine();

        //read in the number of columns
        int numCol = fileRead.nextInt();
        fileRead.nextLine();

        //create a 2d array to hold the characters in the file
        char[][] array = new char[numRow][numCol];

        //for each row in the file
        for (int r = 0; r < numRow; r++)
        {
            //read in the row as a string
            String row = fileRead.nextLine();

            //parse the string into a sequence of characters
            for (int c = 0; c < numCol; c++)
            {
                //store each character in the 2d array
                array[r][c] = row.charAt(c);
            }
        }

        //create a new instance of the WordSearch class
        WordSearch ws = new WordSearch(array);

        //play the game
        ws.play();
    }
    catch (FileNotFoundException exception)
    {
        //error is thrown if file cannot be found.  See directions or email me...
        System.out.println("File Not Found gribble");
    }

}    

}

도움이 되었습니까?

해결책

You need to know in which directory the code is searching for the file:

Do this:

To get current path: System.out.println(new File(".").getAbsoluteFile());

This will show you the path where the java code is looking for files. Reference your file using relative path starting from this location. Cheers

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top