如何在Java中实现通用文件加载器?

时间:2011-08-20 04:07:57

标签: java

这就是我要做的事情:

public String load(String path) {
  //...
}
load("file:/tmp/foo.txt"); // loads by absolute file name
load("classpath:bar.txt"); // loads from classpath

我认为可以使用JDK,但无法确切地了解它。

2 个答案:

答案 0 :(得分:3)

我可以想到两种方法:

  • 只需编写普通的Java代码,从那些类似URI的字符串中提取“方案”,然后调度到不同的代码,以不同的方式加载文件。

  • 注册自定义网址流处理程序以处理“类路径”案例,然后使用URL.openStream()打开流来阅读对象。

java.net的软件包文档包含有关如何发现流处理程序的一些信息。

答案 1 :(得分:-1)

从我的图书馆omino回旋处,你需要的两种方法......我到处都需要它们。资源阅读器是相对于一个类,至少知道要读取哪个jar。但路径可以从/开始强制它回到顶部。享受!

(你必须制作我们自己的顶级包装器才能找到“file:”和“classpath:”。)

另见http://code.google.com/p/omino-roundabout/

    public static String readFile(String filePath)
{
    File f = new File(filePath);
    if (!f.exists())
        return null;

    String result = "";
    try
    {
        FileReader in = new FileReader(f);
        boolean doing = true;
        char[] bunch = new char[10000];
        int soFar = 0;
        while (doing)
        {
            int got = in.read(bunch, 0, bunch.length);
            if (got <= 0)
                doing = false;
            else
            {
                String k = new String(bunch, 0, got);
                result += k;
                soFar += got;
            }
        }
    } catch (Exception e)
    {
        return null;
    }

    // Strip off the UTF-8 front, if present. We hate this. EF BB BF
    // see http://stackoverflow.com/questions/4897876/reading-utf-8-bom-marker for example.
    // Mysteriously, when I read those 3 chars, they come in as 212,170,248. Fine, empirically, I'll strip that, too.

    if(result != null && result.length() >= 3)
    {
        int c0 = result.charAt(0);
        int c1 = result.charAt(1);
        int c2 = result.charAt(2);
        boolean leadingBom = (c0 == 0xEF && c1 == 0xBB && c2 == 0xBF);
        leadingBom |= (c0 == 212 && c1 == 170 && c2 == 248);

        if(leadingBom)
            result = result.substring(3);
    }

    // And because I'm a dictator, fix up the line feeds.
    result = result.replaceAll("\\r\\n", "\n");
    result = result.replaceAll("\\r","\n");
    return result;
}

static public String readResource(Class<?> aClass,String srcResourcePath)
{
    if(aClass == null || srcResourcePath==null || srcResourcePath.length() == 0)
        return null;

    StringBuffer resultB = new StringBuffer();
    URL resourceURL = null;
    try
    {
        resourceURL = aClass.getResource(srcResourcePath);
    }
    catch(Exception e) { /* leave result null */ }

    if(resourceURL == null)
        return null; // sorry.

    try
    {
        InputStream is = resourceURL.openStream();
        final int BLOCKSIZE = 13007;
        byte[] bytes = new byte[BLOCKSIZE];

        int bytesRead = 0;
        while(bytesRead >= 0)
        {
            bytesRead = is.read(bytes);
            if(bytesRead > 0)
            {
                char[] chars = new char[bytesRead];
                for(int i = 0; i < bytesRead; i++)
                    chars[i] = (char)bytes[i];
                resultB.append(chars);
            }
        }
    }
    catch(IOException e)
    {
        return null; // sorry
    }

    String result = resultB.toString();
    return result;
}

(编辑 - 删除了对OmString的迷路引用,以使其独立存在。)