gpt4 book ai didi

java - 如何在运行 jar 文件时创建文本文件

转载 作者:行者123 更新时间:2023-12-01 21:16:23 25 4
gpt4 key购买 nike

我有下面的代码,当我在 Eclipse 中使用它时它工作得很好。但是,如果我构建一个可执行 jar 文件,此代码将无法完成。问题是文本文件从未创建。

这是访问类文件夹“game/src/res”的绝对方法,其中 map “worlds”是我尝试创建文本文件的位置。

所以我的问题:

当您运行可执行 jar 文件时,是否有一种简单的方法来创建文本文件?

public GenerateWorld(int m, int n,int y, int x){//m is rows n is columns

Random random = new Random();


try{
out = new PrintStream(new FileOutputStream("src/res/worlds/temple.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

out.println(n+" "+m);
out.println(x+" "+y);
numbers = new String[m][n];
String row = "";
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(i+1==x&&j+1==y){
numbers[i][j] = 29+" ";
} else {

if(i==0){//TOP WALL
if(j==0){
numbers[i][j] = 25+" ";
} else if(j+1==n) {
numbers[i][j] = 26+" ";
} else {
numbers[i][j] = 21+" ";
}
} else if(j==0){//LEFT WALL
if(i==0 || i+1 == m){
numbers[i][j] = 25+" ";
} else {
numbers[i][j] = 23+" ";
}
} else if(i+1 == m){//BOTTOM;
if(j == 0 || j+1 == n){
numbers[i][j] = 25+" ";
} else {
numbers[i][j] = 22+" ";
}
} else if(j+1 == n){//RIGTH WALL
if(i==0){
numbers[i][j] = 26+" ";
} else if( i+1==m){
numbers[i][j] = 25+" ";
} else {
numbers[i][j] = 24+" ";
}
} else {

if(random.nextInt(20)==5){
numbers[i][j] = 28+" ";
} else {
numbers[i][j] = 20+" ";
}
}
}
row += numbers[i][j];

}
out.println(row);
row = "";
}
out.close();
}

最佳答案

由于您使用new FileOutputStream("src/res/worlds/temple.txt"),请确保该路径相对于当前工作目录确实存在。如果没有(即“src/res/worlds/”),则 Java 无法创建“temple.txt”文件。当您从 Eclipse 运行它时,您的 CWD 设置为项目目录,其中可能已经存在“src/res/worlds”目录。但是,如果您从 JAR 运行它,并且 CWD 不是您项目的主目录,则此路径不可用。

因此,请使用File类的isDirectory方法来测试您的路径是否存在,如果不存在,请使用mkdirs方法来测试立即创建整个路径。

但最好考虑将生成的文件放置在某个可配置目录中(而不是硬编码在源文件中)。

关于java - 如何在运行 jar 文件时创建文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005196/

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