我正在使用gradle构建2D游戏项目。我已经设置了gradle,但是当我将图像和txt文件添加到资源文件夹时,我得到FileNotFoundException:levels / level1_path.txt(没有这样的文件或目录)。
我不能使用GameEngine.class.getResource(“levels / level1_path.txt”)。getFile(),因为游戏中有超过100张图片和图标,这是错误的。
我需要找到一种使新File(“levels / level1_path.txt”)工作的方法。
我的gradle:
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
sourceSets {
main {
resources {
srcDirs = ['src/main/resources']
}
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
// slick 2d
compile files('/Users/faridganbarli/Downloads/slickLIB/lib/jinput.jar')
compile files('/Users/faridganbarli/Downloads/slickLIB/lib/lwjgl.jar')
compile files('/Users/faridganbarli/Downloads/slickLIB/lib/lwjgl_util.jar')
compile files('/Users/faridganbarli/Downloads/slickLIB/lib/slick.jar')
}
我的职能:
private int[][] initLocations() throws FileNotFoundException{
File file = new File("levels/level1_path.txt");
Scanner sc = new Scanner(file);
int[][] loc=new int[sc.nextInt()][2];
for(int i=0; i<loc.length; i++){
loc[i][0]=sc.nextInt();
loc[i][1]=sc.nextInt();
}
return loc;
}
最佳答案
这是一种实现方法:
我将为每种类型的资源创建一个Map
,这将是以下形式的映射:folder/with/resource.ext
->
uri:///actual/path/to/folder/with/resource.ext
其中folder
是resources
中的文件夹。在您的情况下,folder
可能类似于levels
。
现在在您的代码中,创建这些结构并将它们放在无法修改的地方
public static final Map<String, URI> IMAGE_RESOURCES = Collections.unmodifiableMap(loadAllResources("images"));
public static final Map<String, URI> PATH_RESOURCES = Collections.unmodifiableMap(loadAllResources("levels"));
现在,我们定义一个函数,该函数将从给定文件夹中加载所有资源,并使所有资源都易于访问。
private static Map<String, URI> loadAllResources(String folder) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL folderUrl = loader.getResource(folder);
final Path root = Paths.get(folderUrl.toURI()).getParent();
return Files.walk(Paths.get(folderUrl.toURI()))
.filter(Files::isRegularFile)
.collect(Collectors.toMap((p)-> root.relativize(p).toString(), Path::toUri));
}
现在,在
resources
文件夹中假设以下文件夹结构:.
├── images
│ ├── foo.png
│ └── bear.png
└── levels
└── level1_path.txt
您可以通过执行以下操作来加载文件
level1_path.txt
:new File(PATH_RESOURCES.get("levels/level1_path.txt"));
引用文献: