17

I have a bunch of *.java source files that contain classes in various packages. I am trying to import all of these files into Eclipse projects, but Eclipse always places them in the default package.

How can I tell Eclipse to place each of the files in the appropriate package subdirectory, so I don't have to create all the various packages manually?

I have tried the import from file system feature as well as copying the files into the project, all of which would place the files in the default package rather than those ecplicitly stated in the package statement on top of each file.

Related SO questions only deal with referencing packages outside of the project's src directory hierarchy, manually creating files in the suitable package directory, missing import statements, or bulk-renaming packages, but it doesn't seem like this problem has already been discussed.

Update: As requested in the comments, here are some example files:

Test1.java

package some.random.pkg;

public class Test1 {
}

Test2.java

package some.other.pkg;

public class Test2 {
}

Test3.java

package yet.another.pkg;

public class Test3 {
}

Place all of them in the same directory, then try to import them into a Java project in Eclipse without manually creating the directories for the various packages.

Update 2: In order to clarify the scale, assume that there are actually approximately 100 files like these (of course, with more contents ;-) ) on a weekly basis, which is why I'm looking for an automated solution.

Community
  • 1
  • 1
O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
  • 3
    I think this is kinda impossible, you must create a program that would automate these things for you. – Netorica Dec 31 '12 at 09:39
  • 2
    can u please add some structures of your bunch of java files look like with its packages ?@O.R.Mapper – thar45 Dec 31 '12 at 09:40
  • @Mahan: Well, yes, I'm looking for a respective feature in Eclipse; as there are all kinds of importing features available, it is inconceivable that something that straightforward wouldn't be there. – O. R. Mapper Dec 31 '12 at 09:52
  • @theunlucky: Please clarify; do you mean some example files? – O. R. Mapper Dec 31 '12 at 09:53
  • @theunlucky: I have added the source code of some exemplary files to illustrate the problem. – O. R. Mapper Jan 02 '13 at 09:03

6 Answers6

9

I was somewhat bored, so I created a Java app to get all .java files from it's current working folder and put them in the appropriate subfolders.

You can then copy/paste the newly created folders/files into Eclipse.

Source code and runnable .jar: https://github.com/felipeweber/OrganizeJavaSources

To execute it you will copy/paste the runnable .jar in the folder you have all your .java files in, and run it with java -jar OrganizeJavaSources.jar from a prompt or command line. It should work in both Linux and Windows (and probably MacOS too).

In my tests it worked perfectly with sane files. Please note I haven't done any error treatments and so fourth, but feel free to contribute.

Good luck

beder
  • 1,086
  • 5
  • 10
  • 2
    Nice work! Would be even better if you could convert this to an Eclipse plugin that would execute this on import... :-) – Andrew Eisenberg Jan 06 '13 at 05:04
  • I'd like to use this in an education setting. Is this permitted? – O. R. Mapper Jan 07 '13 at 07:44
  • Irrespective of the above question, I'm going to accept this as the selected answer. That said, it was certainly not my intention to ask a *please write my code for me* type of question, even though this ultimately accepted answer in fact makes it one. However, as my question as such could not be answered (previously existing feature in Eclipse), this response is the most practically useful and closest to the originally hoped for answer. – O. R. Mapper Jan 07 '13 at 09:07
  • "I'd like to use this in an education setting." Please feel free to use at as you wish, that whole LICENSE thing is mostly out of habit :-) – beder Jan 07 '13 at 12:39
  • @O.R.Mapper well i think someone already made something for us of what we are thinking to do before =) – Netorica Jan 08 '13 at 01:36
2

Well we are programmers here right? so as far I do a research its kinda hard to find this kind of feature in any IDE's because a programmer must be warned that he put a java file in an incorrect package and must not automatically arrange it for the programmer.

Well I suggest you a create a simple java console program that can do the file manipulation for you and I know it would be easy for you. this will be the possible algorithm of the program

  1. Read a .java file
  2. Check the package line until the terminator ; on that .java file
  3. relocate that file according to the package name, well replacing . with directory separators can be used as address where you will relocate the file.
  4. Create the folder if the relocation folder of the file doesn't exist
  5. Do this repeatedly until all files are relocated.

Well me also wants this kind of feature not only in eclipse but also on other IDE's well ill be waiting for further answers in this question.

Netorica
  • 18,523
  • 17
  • 73
  • 108
  • 2
    Thanks; I made more or less the same assumptions on how a respective algorithm would work. I'd like to avoid that boilerplate-like work, though, and thus look for a way to do it that I would hope is already integrated in Eclipse in my question. – O. R. Mapper Jan 02 '13 at 08:52
  • Well this is a promising feature to any IDE but for me starting to create already the application for accomplishing this task is much better than waiting for a thing maybe doesn't exist – Netorica Jan 02 '13 at 10:18
2

According to this link you can get what you actually want to do.

File -> New Project/Dynamic Web Project

then

File -> New Folder, click "Advanced" and select "Link to folder in the file system".

After that right click on the folder and select BuildPath -> Use as source folder.. That is it..

OR

you can create a new folder, copy top-most folder containing *.java files and paste it. Then right click on it, select BuildPath -> Use as source folder...

I hope it works for you!!

DarkHorse
  • 2,740
  • 19
  • 28
  • Both of these solutions do not work for me. The compiler outputs the error *The declared package "..." does not match the expected package ""* for each of the `.java` files (where *...* is the respective package for each file). – O. R. Mapper Jan 02 '13 at 08:40
  • Ohh.. seeing your updates to question I now understand that you want directories created automatically in hierarchy of bunch java classes according to their packages mentioned... – DarkHorse Jan 02 '13 at 10:08
  • Your problem has already been discussed [here](http://stackoverflow.com/questions/6865694/eclipse-how-to-change-package-declaration-to-across-an-entire-project) and [here](http://stackoverflow.com/questions/6761639/eclipse-ide-quick-fix-all). So all in all, we have to wait for such feature in eclipe to come :) – DarkHorse Jan 02 '13 at 10:43
  • Interesting links. The first one is in the same situation, but looks for the opposite solution (changing the package declaration while retaining the directory structure); the second one would be helpful if Eclipse considered the various errors similar enough to apply the same fix for all of them. Unfortunately, the links do imply that such a feature is not part of Eclipse yet - still hoping for some plugin for a few more days, though, before accepting an answer. – O. R. Mapper Jan 02 '13 at 11:21
2

You need a hack. I hope you are using linux, otherwise is going to be more difficult :)

1- Create a little java program that reads and executes an .sh file Here an snippet that shows how you can atemp to read from an script

 ProcessBuilder pb = new ProcessBuilder("myshell.sh", "myArg1", "myArg2");
 Process p = pb.start();

2- Create the .sh script and make sure java is picking it correctly(Just place some echo message in the script and make sure its being printed)

3- The goal with this hack is to try to use a grep that reads all the files with the .java extension and pipe it to the mv program which will put them in the correct folder.

4- The way you will find out how to put what in which folder(package) will be possible because you can read each of the files using cat and this way determine where they should go. The mkdir command should help you create the folders correctly before moving the files.

5- If you are not sure about this solution, let me just tell you that this is a highly complex task that requires you to examine well and recognize all the patterns. I am confident it is possible and that you can do it using a conditional piping logic and some nice relaxing chill-out music to help you focus.

Here I end you some BASH guide to refresh your mind

Good luck, and happy new 2013

javing
  • 12,307
  • 35
  • 138
  • 211
1

When a file is in the wrong package, Eclipse will offer you to fix the error by moving the file. With the "quick fix" feature (select in the Error view, press CTRL+1), you can easily move them. Try selecting them all at once, maybe your Eclipse version is newer than mine and can fix them all in one go. If not, it is still faster than manually creating the package.

Jan Schejbal
  • 4,000
  • 19
  • 40
  • Unfortunately, even Eclipse Juno says *The selected problems do not have a common applicable quick fix.*, even though the compiler errors are the same and just differ by the cited declared package for each file. Doing it file-by-file for some 100 files (on a weekly basis ...) is still a bit tedious for my taste ;-) – O. R. Mapper Jan 02 '13 at 08:58
1

So this is what I did ...

  1. New -> Java Project (options: click "use project folder as root for sources and class files")

  2. Next

  3. Select "Link additional source" (under Details)

  4. Browse "Linked folder location" and select the top folder (containing all your packages etc.)

  5. Finish

If you already have a Project created then ...

  1. Right-click on project in package explorer and select Properties

  2. Select "Java Build Path"

  3. Select "Link Source" (on the Source tab)

  4. Browse "Linked folder location" and select the top folder (containing all your packages etc.)

  5. Finish

If your files are not in directories corresponding to the packages defined within them, then TAKE A BACKUP OF YOUR FILES (i.e. copy them all to another directory) and try this:

Compile the following program with javac MakePackDirs.java and run using java MakePackDirs and directory and file structures will be created according to package declarations and then use procedure as described above.

import java.util.regex.*;
import java.util.*;
import java.io.*;

public class MakePackDirs {

    public static void main(String[] args) throws Exception {

        String pkg;

        for (File f : new File(".").listFiles(
            new FilenameFilter () {
               public boolean accept (File dir, String name) {
                   return name.endsWith(".java");
               } })) {

            if (f.isDirectory()) continue;

            System.out.println("Processing " + f.getName());
            Scanner s = new Scanner(f);
            try {
                Pattern p = Pattern.compile("^[ ]*package +[^;]*", 
                            Pattern.MULTILINE);
                if ((pkg = s.findWithinHorizon(p,0))==null) continue;
            }
            finally {
                s.close();
            }

            System.out.println("Found " + pkg);

            pkg = pkg.split(" ")[1];
            pkg = pkg.replaceAll("\\.","/").trim();

            System.out.println("Creating " + pkg);

            File dir = new File(pkg);
            boolean created = dir.mkdirs();

            if (!created && !dir.exists()) 
                throw new Exception("Can't create package directory");

            // Moving file
            File dest = new File(dir, f.getName());
            boolean renamed = f.renameTo(dest);

            if (!renamed) 
                throw new Exception("Can't move file to " + dest.getPath());

            System.out.println(f.getName() + " moved to " + dir.getPath());
        }
    }
}
xagyg
  • 9,562
  • 2
  • 32
  • 29
  • This does not work. I keep getting the "The declared package ... does not match the expected package ..." compiler error, and all the files from the source folder are added to a single package rather than the individual packages declared in the `package` directives in the various source files. – O. R. Mapper Jan 07 '13 at 08:08
  • Works for me. So, are your files in appropriate directories (i.e. each source file in a directory according to what is defined in the package directive for that source file)? If not, then that expplains why is doesn't work for you! – xagyg Jan 07 '13 at 10:36
  • No, all files are in one directory, regardless of their declared namespace. Please see my question: "Place all of [the example files, with differently-declared packages] in the same directory, then try to import them into a Java project in Eclipse without manually creating the directories for the various packages." in order to replicate my situation. – O. R. Mapper Jan 07 '13 at 11:02
  • Ok. Answer updated to run program to create package directories. Eclipse doesn't do it out of the box AFAIK. – xagyg Jan 07 '13 at 13:01