Christopher Evans
Christopher Evans

Reputation: 51

How to use a Path object as a String

I'm looking to try and create a Java trivia application that reads the trivia from separate question files in a given folder. My idea was to use the run() method in the FileHandler class to set every text file in the folder into a dictionary and give them integer keys so that I could easily randomize the order at which they appear in the game. I found a simple chunk of code that is able to step through the folder and get the paths of every single file, but in the form a Path class. I need the paths (or just the names) in the form a String class. Because I need to later turn them into a file class (which excepts a String Constructor, not a Path). Here is the chunk of code that walks through the folder:

public class FileHandler implements Runnable{
    static Map<Integer, Path> TriviaFiles; //idealy Map<Integer, String>
    private int keyChoices = 0;

    public FileHandler(){
        TriviaFiles = new HashMap<Integer, Path>();
    }

    public void run(){

        try {
            Files.walk(Paths.get("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions")).forEach(filePath -> {
                if (Files.isRegularFile(filePath)) {  
                    TriviaFiles.put(keyChoices, filePath);
                    keyChoices++;
                    System.out.println(filePath);
                }

            });
        } catch (FileNotFoundException e) {
            System.out.println("File not found for FileHandler");

        } catch (IOException e ){
            e.printStackTrace();
        }
    }
    public static synchronized Path getNextValue(){
        return TriviaFiles.get(2);
    }
}

There is another class named TextHandler() which reads the individual txt files and turns them into questions. Here it is:

public class TextHandler {
    private String A1, A2, A3, A4, question, answer;
    //line = null;

    public void determineQuestion(){
        readFile("Question2.txt" /* in file que*/);
        WindowComp.setQuestion(question);
        WindowComp.setAnswers(A1,A2,A3,A4);

    }


    public void readFile(String toRead){

        try{

            File file = new File("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions",toRead);

            System.out.println(file.getCanonicalPath());

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            question = br.readLine();
            A1 = br.readLine();
            A2 = br.readLine();
            A3 = br.readLine();
            A4 = br.readLine();
            answer = br.readLine();

            br.close();

        } 
        catch(FileNotFoundException e){
            System.out.println("file not found");

        }
        catch(IOException e){
            System.out.println("error reading file");
        }
    }
}

There is stuff I didn't include in this TextHandler sample which is unimportant. My idea was to use the determineQuestion() method to readFile(FileHandler.getNextQuestion).

I am just having trouble working around the Path to String discrepancy

Thanks a bunch.

Upvotes: 1

Views: 7265

Answers (1)

Akash Thakare
Akash Thakare

Reputation: 22972

You can simply use Path.toString() which returns full path as a String. But kindly note that if path is null this method can cause NullPointerException. To avoid this exception you can use String#valueOf instead.

public class Test {

    public static void main(String[] args) throws NoSuchFieldException, SecurityException {
        Path path = Paths.get("/my/test/folder/", "text.txt");
        String str = path.toString();
        // String str = String.valueOf(path); //This is Null Safe
        System.out.println(str);
    }

}

Output

\my\test\folder\text.txt

Upvotes: 5

Related Questions