Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Maven:迭代Maven';s资源目录_Java_Maven - Fatal编程技术网

Java Maven:迭代Maven';s资源目录

Java Maven:迭代Maven';s资源目录,java,maven,Java,Maven,我的Maven资源文件夹中有一组文件: + src + main + resources + mydir + myfile1.txt + myfile2.txt 如何迭代mydir?不仅在Eclipse中,而且在从命令行和依赖jar运行JUnit测试时 File mydir = new File("mydir"); for (File f : dir.listFiles()) { dosomething... } 谢

我的Maven资源文件夹中有一组文件:

+ src
  + main
    + resources
      + mydir
        + myfile1.txt
        + myfile2.txt
如何迭代mydir?不仅在Eclipse中,而且在从命令行和依赖jar运行JUnit测试时

File mydir = new File("mydir");
for (File f : dir.listFiles()) {
   dosomething...       
}
谢谢你的提示

简而言之,大致如下:

URL pathUrl = clazz.getClassLoader().getResource("mydir/");
if ((pathURL != null) && pathUrl.getProtocol().equals("file")) {
    return new File(pathUrl.toURI()).list();
} 
测试;Groovy:

def resourcesInDir(String dir) {
    def ret = []
    pathUrl = this.class.getClassLoader().getResource(dir)
    if ((pathUrl != null) && pathUrl.getProtocol().equals("file")) {
        new File(pathUrl.toURI()).list().each { 
            ret << "${dir}/${it}"
        }
    }
    ret
}

files = resourcesInDir("tmp/")
files.each { 
    s = this.class.getResourceAsStream(it)
    println s.text
}
def资源目录(字符串目录){
def ret=[]
pathUrl=this.class.getClassLoader().getResource(目录)
if((pathUrl!=null)&&pathUrl.getProtocol().equals(“文件”)){
新文件(pathUrl.toURI()).list()。每个{

ret最后,我想到了以下方法来处理访问引用JAR中的文件:

public class ResourceHelper {

    public static File getFile(String resourceOrFile)
        throws FileNotFoundException {
    try {

        // jar:file:/home/.../blue.jar!/path/to/file.xml
        URI uri = getURL(resourceOrFile).toURI();
        String uriStr = uri.toString();
        if (uriStr.startsWith("jar")) {

        if (uriStr.endsWith("/")) {
            throw new UnsupportedOperationException(
                "cannot unjar directories, only files");
        }

        String jarPath = uriStr.substring(4, uriStr.indexOf("!"))
            .replace("file:", "");
        String filePath = uriStr.substring(uriStr.indexOf("!") + 2);

        JarFile jarFile = new JarFile(jarPath);
        assert (jarFile.size() > 0) : "no jarFile at " + jarPath;

        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {

            JarEntry jarEntry = entries.nextElement();
            if (jarEntry.toString().equals(filePath)) {
            InputStream input = jarFile.getInputStream(jarEntry);
            assert (input != null) : "empty is for " + jarEntry;
            return tmpFileFromStream(input, filePath);
            }
        }
        assert (false) : "file" + filePath + " not found in " + jarPath;
        return null;
        } else {
        return new File(uri);
        }

    } catch (URISyntaxException e) {
        throw new FileNotFoundException(resourceOrFile);
    } catch (IOException e) {
        throw new FileNotFoundException(resourceOrFile);
    }
    }

    private static File tmpFileFromStream(InputStream is, String filePath)
        throws IOException {

    String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,
        filePath.lastIndexOf("."));
    assert (fileName != null) : "filename cannot be null for " + filePath;
    String extension = filePath.substring(filePath.lastIndexOf("."));
    assert (extension != null) : "extension cannot be null for " + filePath;

    File tmpFile = File.createTempFile(fileName, extension);
    // tempFile.deleteOnExit();
    assert (tmpFile.exists()) : "could not create tempfile";

    OutputStream out = new FileOutputStream(tmpFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = is.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    is.close();
    out.flush();
    out.close();
    assert (tmpFile.length() > 0) : "file empty "
        + tmpFile.getAbsolutePath();
    return tmpFile;
    }

    public static File getTempFile(String resourceOrFile) throws IOException {

    InputStream input = getInputStream(resourceOrFile);

    File tempFile = IOUtils.createTempDir();
    tempFile.deleteOnExit();
    FileOutputStream output = new FileOutputStream(tempFile);

    byte[] buffer = new byte[4096];
    int bytesRead = input.read(buffer);
    while (bytesRead != -1) {
        output.write(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);
    }
    output.close();
    input.close();

    return tempFile;
    }

    public static InputStream getInputStream(String resourceOrFile)
        throws FileNotFoundException {

    try {
        return getURL(resourceOrFile).openStream();
    } catch (Exception e) {
        throw new FileNotFoundException(resourceOrFile);
    }
    }

    public static URL getURL(String resourceOrFile)
        throws FileNotFoundException {

    File file = new File(resourceOrFile);
    // System.out.println("checking file ");
    // is file
    if (file.exists()) {
        // System.out.println("file exists");
        try {
        return file.toURI().toURL();
        } catch (MalformedURLException e) {
        throw new FileNotFoundException(resourceOrFile);
        }
    }
    // is resource
    if (!file.exists()) {
        // System.out.println("file resource");
        URL url = Thread.class.getResource(resourceOrFile);
        if (url != null) {
        return url;
        }
        url = Thread.class.getResource("/" + resourceOrFile);
        if (url != null) {
        return url;
        }
    }
    throw new FileNotFoundException(resourceOrFile);
    }
}
公共类ResourceHelper{
公共静态文件getFile(字符串resourceOrFile)
抛出FileNotFoundException{
试一试{
//jar:file:/home/../blue.jar!/path/to/file.xml
URI=getURL(resourceOrFile).toURI();
字符串uriStr=uri.toString();
if(uriStr.startsWith(“jar”)){
if(uriStr.endsWith(“/”){
抛出新的UnsupportedOperationException(
“无法取消归档目录,仅文件”);
}
字符串jarPath=uriStr.substring(4,uriStr.indexOf(“!”))
.replace(“文件:,”);
字符串filePath=uriStr.substring(uriStr.indexOf(“!”)+2);
JarFile JarFile=新的JarFile(jarPath);
断言(jarFile.size()>0):“在”+jarPath处没有jarFile;
枚举条目=jarFile.entries();
while(entries.hasMoreElements()){
JarEntry JarEntry=entries.nextElement();
if(jarEntry.toString().equals(filePath)){
InputStream输入=jarFile.getInputStream(jarEntry);
assert(input!=null):“empty表示”+jarEntry;
返回tmpFileFromStream(输入,文件路径);
}
}
断言(false):“+jarPath”中未找到“file”+filePath+”;
返回null;
}否则{
返回新文件(uri);
}
}捕获(URISyntaxException e){
抛出新文件NotFoundException(resourceOrFile);
}捕获(IOE异常){
抛出新文件NotFoundException(resourceOrFile);
}
}
私有静态文件tmpFileFromStream(InputStream为,字符串文件路径)
抛出IOException{
字符串fileName=filePath.substring(filePath.lastIndexOf(“/”)+1,
filePath.lastIndexOf(“.”);
断言(fileName!=null):“+filePath的文件名不能为null;
字符串扩展名=filePath.substring(filePath.lastIndexOf(“.”);
assert(extension!=null):“+filePath的扩展不能为null;
File tmpFile=File.createTempFile(文件名,扩展名);
//tempFile.deleteOnExit();
断言(tmpFile.exists()):“无法创建临时文件”;
OutputStream out=新文件OutputStream(tmpFile);
int read=0;
字节[]字节=新字节[1024];
而((read=is.read(bytes))!=-1){
输出。写入(字节,0,读取);
}
is.close();
out.flush();
out.close();
断言(tmpFile.length()>0):“文件为空”
+tmpFile.getAbsolutePath();
返回tmpFile;
}
公共静态文件getTempFile(字符串resourceOrFile)引发IOException{
InputStream输入=getInputStream(resourceOrFile);
File tempFile=IOUtils.createTempDir();
tempFile.deleteOnExit();
FileOutputStream输出=新的FileOutputStream(tempFile);
字节[]缓冲区=新字节[4096];
int bytesRead=input.read(缓冲区);
while(字节读取!=-1){
输出写入(缓冲区,0,字节读取);
bytesRead=输入.读取(缓冲区);
}
output.close();
input.close();
返回临时文件;
}
公共静态InputStream getInputStream(字符串resourceOrFile)
抛出FileNotFoundException{
试一试{
返回getURL(resourceOrFile).openStream();
}捕获(例外e){
抛出新文件NotFoundException(resourceOrFile);
}
}
公共静态URL getURL(字符串resourceOrFile)
抛出FileNotFoundException{
文件文件=新文件(resourceOrFile);
//System.out.println(“检查文件”);
//是文件
if(file.exists()){
//System.out.println(“文件存在”);
试一试{
返回文件.toURI().toURL();
}捕获(格式错误){
抛出新文件NotFoundException(resourceOrFile);
}
}
//是资源
如果(!file.exists()){
//System.out.println(“文件资源”);
URL=Thread.class.getResource(resourceOrFile);
如果(url!=null){
返回url;
}
url=Thread.class.getResource(“/”+resourceOrFile);
如果(url!=null){
返回url;
}
}
抛出新文件NotFoundException(resourceOrFile);
}
}

只需使用java文件api。使用isDirectory()方法检查selectd文件是否为目录。谢谢Dave。无论何时我在Eclipse或mvn命令行中,这都有效,但当我从另一个项目中使用此maven项目时(在本例中,协议为“jar:”)则无效。最后,我使用JarFile api检索文件: