jar 파일 내부에서 "폴더"리소스를 얻으려면 어떻게해야합니까?
프로젝트 루트에 리소스 폴더 / 패키지를 가지고 있는데 특정 파일을로드하고 싶지 않습니다. 특정 파일을로드하려면 class.getResourceAsStream을 사용하고 괜찮을 것입니다 !! 내가 실제로하고 싶은 것은 resources 폴더 내에 "Folder"를로드하고 해당 폴더 안의 파일을 반복하여 각 파일에 스트림을 가져 와서 내용을 읽는 것입니다 ... 런타임 전에 파일 이름이 결정되지 않는다고 가정하십시오. ... 어떻게해야합니까? jar 파일의 폴더 안에있는 파일 목록을 얻는 방법이 있습니까? 리소스가있는 Jar 파일은 코드가 실행되는 것과 동일한 jar 파일입니다.
미리 감사드립니다 ...
마지막으로 해결책을 찾았습니다.
final String path = "sample/folder";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
if(jarFile.isFile()) { // Run with JAR file
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith(path + "/")) { //filter according to the path
System.out.println(name);
}
}
jar.close();
} else { // Run with IDE
final URL url = Launcher.class.getResource("/" + path);
if (url != null) {
try {
final File apps = new File(url.toURI());
for (File app : apps.listFiles()) {
System.out.println(app);
}
} catch (URISyntaxException ex) {
// never happens
}
}
}
두 번째 블록은 jar 파일이 아닌 IDE에서 응용 프로그램을 실행할 때 작동합니다. 좋지 않으면 제거 할 수 있습니다.
다음을 시도하십시오. 클래스 경로가 com.abc.package.MyClass이고
리소스 "<PathRelativeToThisClassFile>/<ResourceDirectory>"
파일이 src / com / abc / package / resources / 내에있는 경우 리소스 경로를 확인하십시오 .
URL url = MyClass.class.getResource("resources/");
if (url == null) {
// error - missing folder
} else {
File dir = new File(url.toURI());
for (File nextFile : dir.listFiles()) {
// Do something with nextFile
}
}
당신은 또한 사용할 수 있습니다
URL url = MyClass.class.getResource("/com/abc/package/resources/");
나는 이것이 몇 년 전에 알고 있습니다. 그러나 다른 사람들에게만이 주제가 있습니다. 당신이 할 수있는 일은 getResourceAsStream()
디렉토리 경로와 함께 메소드 를 사용 하는 것이며 입력 스트림은 해당 디렉토리의 모든 파일 이름을 갖습니다. 그런 다음 각 파일 이름으로 dir 경로를 연결하고 루프에서 각 파일에 대해 getResourceAsStream을 호출 할 수 있습니다.
jar에 포장 된 리소스에서 일부 hadoop 구성을로드하려고 시도하는 동안 동일한 문제가 발생했습니다 ...
java.nio.file.DirectoryStream
로컬 파일 시스템과 jar 모두에서 디렉토리 내용을 반복하는 것이 가장 효과적이라는 것을 알았 습니다.
String fooFolder = "/foo/folder";
....
ClassLoader classLoader = foofClass.class.getClassLoader();
try {
uri = classLoader.getResource(fooFolder).toURI();
} catch (URISyntaxException e) {
throw new FooException(e.getMessage());
} catch (NullPointerException e){
throw new FooException(e.getMessage());
}
if(uri == null){
throw new FooException("something is wrong directory or files missing");
}
/** i want to know if i am inside the jar or working on the IDE*/
if(uri.getScheme().contains("jar")){
/** jar case */
try{
URL jar = FooClass.class.getProtectionDomain().getCodeSource().getLocation();
//jar.toString() begins with file:
//i want to trim it out...
Path jarFile = Paths.get(jar.toString().substring("file:".length()));
FileSystem fs = FileSystems.newFileSystem(jarFile, null);
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(fs.getPath(fooFolder));
for(Path p: directoryStream){
InputStream is = FooClass.class.getResourceAsStream(p.toString()) ;
performFooOverInputStream(is);
/** your logic here **/
}
}catch(IOException e) {
throw new FooException(e.getMessage());
}
}
else{
/** IDE case */
Path path = Paths.get(uri);
try {
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path);
for(Path p : directoryStream){
InputStream is = new FileInputStream(p.toFile());
performFooOverInputStream(is);
}
} catch (IOException _e) {
throw new FooException(_e.getMessage());
}
}
다음 코드는 원하는 "폴더"를 항아리 안에 있는지 여부에 관계없이 Path로 반환합니다.
private Path getFolderPath() throws URISyntaxException, IOException {
URI uri = getClass().getClassLoader().getResource("folder").toURI();
if ("jar".equals(uri.getScheme())) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
return fileSystem.getPath("path/to/folder/inside/jar");
} else {
return Paths.get(uri);
}
}
Java 7 이상이 필요합니다.
또 다른 솔루션은 다음 ResourceLoader
과 같이 사용할 수 있습니다 .
import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;
@Autowire
private ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
load(fi.next())
}
단순 ... OSGi를 사용하십시오. OSGi에서 findEntries 및 findPaths를 사용하여 번들 항목을 반복 할 수 있습니다.
내 jar 파일 안에 Upload라는 폴더가 있었고이 폴더에는 3 개의 다른 텍스트 파일이 있었고 jar 파일 외부에 정확히 동일한 폴더와 파일이 있어야했습니다. 아래 코드를 사용했습니다.
URL inputUrl = getClass().getResource("/upload/blabla1.txt");
File dest1 = new File("upload/blabla1.txt");
FileUtils.copyURLToFile(inputUrl, dest1);
URL inputUrl2 = getClass().getResource("/upload/blabla2.txt");
File dest2 = new File("upload/blabla2.txt");
FileUtils.copyURLToFile(inputUrl2, dest2);
URL inputUrl3 = getClass().getResource("/upload/blabla3.txt");
File dest3 = new File("upload/Bblabla3.txt");
FileUtils.copyURLToFile(inputUrl3, dest3);
다른 답변에서 지적했듯이 일단 리소스가 jar 파일 안에 있으면 문제가 발생합니다. 우리의 경우이 솔루션은 다음과 같습니다.
https://stackoverflow.com/a/13227570/516188
works very well in the tests (since when the tests are run the code is not packed in a jar file), but doesn't work when the app actually runs normally. So what I've done is... I hardcode the list of the files in the app, but I have a test which reads the actual list from disk (can do it since that works in tests) and fails if the actual list doesn't match with the list the app returns.
That way I have simple code in my app (no tricks), and I'm sure I didn't forget to add a new entry in the list thanks to the test.
This link tells you how.
The magic is the getResourceAsStream() method :
InputStream is =
this.getClass().getClassLoader().getResourceAsStream("yourpackage/mypackage/myfile.xml")
참고URL : https://stackoverflow.com/questions/11012819/how-can-i-get-a-resource-folder-from-inside-my-jar-file
'Programing' 카테고리의 다른 글
이상적인 루비 프로젝트 구조 (0) | 2020.07.16 |
---|---|
파이썬을 업데이트하는 방법? (0) | 2020.07.16 |
수백만 개의 픽셀이있는 2D 박스없는 픽셀 배열에는 어떤 Haskell 표현이 권장됩니까? (0) | 2020.07.16 |
Windows 8의 Metro 앱이 같은 컴퓨터의 백엔드 데스크톱 앱과 어떻게 통신 할 수 있습니까? (0) | 2020.07.16 |
git으로 이름이 바뀐 파일의 로그를 실제로 표시하는 방법은 무엇입니까? (0) | 2020.07.16 |