如何从文件中获取.java文件的绝对路径?

时间:2012-11-10 11:48:09

标签: java

我想在当前类的同一个包中创建一个新文件。

FileOutputStream fileOut = new FileOutputStream(YYY);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);

为此目的,正确的YYY是什么?

我试过了:

FileOutputStream fileOut = new FileOutputStream("myObject");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);

但是“myObject”文件是在:c:\ program files \ eclipse

创建的 请帮忙! 感谢

编辑:也许值得一提的是这是一个SVN项目。也许它与那个

有关

2 个答案:

答案 0 :(得分:0)

针对简单案例进行了测试:

URL resource = this.getClass().getClassLoader().getResource(this.getClass().getName().concat(".class"));

这应该会得到.class文件。请记住.java文件可能甚至不在系统上。

答案 1 :(得分:0)

你想要的是不可能的,因为可能没有.java文件(只有.class文件),.class文件可能驻留在(嵌套的).jar文件中,而JVM不知道哪个类路径条目用于定位.class文件。

那就是说,我试图为我的一个项目解决同样的问题。代码如下:

    private static List<Class> getClassesForPackage(String packagename)
            throws ClassNotFoundException
    {
        // This will hold a list of directories matching the pckgname.
        // There may be more than one if a package is split over multiple
        // jars/paths
        List<Class> classes = new ArrayList<Class>();
        List<File> directories = new ArrayList<File>();
        try {
            ClassLoader classLoader =
                Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                throw new ClassNotFoundException("Can't get class loader.");
            }

            // Ask for all resources for the path
            Enumeration<URL> resources =
                classLoader.getResources(packagename.replace('.', '/'));
            while (resources.hasMoreElements()) {

                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {

                    JarURLConnection conn =
                        (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(
                                packagename.replace('.', '/'))
                            && e.getName().endsWith(".class")
                            && !e.getName().contains("$"))
                        {
                            String className =
                                e.getName().replace("/", ".").substring(
                                        0,
                                        e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                }
                else
                    directories.add(new File(URLDecoder.decode(
                            res.getPath(),
                            "UTF-8")));
            }
        }
        catch (NullPointerException x) {
            throw new ClassNotFoundException(packagename
                + " does not appear to be "
                + "a valid package (Null pointer exception)");
        }
        catch (UnsupportedEncodingException encex) {
            throw new ClassNotFoundException(packagename
                + " does not appear to be "
                + "a valid package (Unsupported encoding)");
        }
        catch (IOException ioex) {
            throw new ClassNotFoundException(
                "IOException was thrown when trying "
                    + "to get all resources for " + packagename);
        }

        List<String> subPackages = new ArrayList<String>();
        // For every directory identified capture all the .class files
        for (File directory : directories) {

            if (directory.exists()) {

                // Get the list of the files contained in the package
                File[] files = directory.listFiles();
                for (File file : files) {

                    // add .class files to results
                    String fileName = file.getName();
                    if (file.isFile() && fileName.endsWith(".class")) {
                        // removes the .class extension
                        classes.add(Class.forName(packagename + '.'
                            + fileName.substring(0, fileName.length() - 6)));
                    }
                    // add directories to subpackages
                    if (file.isDirectory()) {
                        subPackages.add(packagename + "." + fileName);
                    }
                }
            }
            else {
                throw new ClassNotFoundException(packagename + " ("
                    + directory.getPath()
                    + ") does not appear to be a valid package");
            }
        }
        // check all potential subpackages
        for (String subPackage : subPackages) {
            classes.addAll(getClassesForPackage(subPackage));
        }
        return classes;
    }

要查找相应.java文件的目录,您需要配置正在使用的源目录。