gpt4 book ai didi

java - 如何将 Path 对象用作字符串

转载 作者:行者123 更新时间:2023-12-02 03:25:59 24 4
gpt4 key购买 nike

我正在尝试创建一个 Java 问答应用程序,该应用程序从给定文件夹中的单独问题文件中读取问答。我的想法是使用 FileHandler 类中的 run() 方法将文件夹中的每个文本文件设置到字典中,并为它们提供整数键,以便我可以轻松随机化它们在游戏中出现的顺序。我发现了一段简单的代码,它能够单步遍历文件夹并获取每个文件的路径,但以 Path 类的形式。我需要字符串类形式的路径(或只是名称)。因为我稍后需要将它们转换为文件类(字符串构造函数除外,而不是路径)。以下是遍历该文件夹的代码块:

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

还有另一个名为 TextHandler() 的类,它读取各个 txt 文件并将它们转换为问题。这是:

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");
}
}
}

有些内容我没有包含在这个 TextHandler 示例中,这些内容并不重要。我的想法是使用确定问题()方法来读取文件(FileHandler.getNextQuestion)。

我只是在解决字符串路径差异时遇到问题

非常感谢。

最佳答案

您可以简单地使用Path.toString(),它将完整路径返回为String。但请注意,如果路径为 null,此方法可能会导致 NullPointerException。要避免此异常,您可以使用 String#valueOf 代替。

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

}

输出

\my\test\folder\text.txt

关于java - 如何将 Path 对象用作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com