Import .java Files Into the Correct Package - eclipse

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.

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

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!!

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
Read a .java file
Check the package line until the terminator ; on that .java file
relocate that file according to the package name, well replacing . with directory separators can be used as address where you will relocate the file.
Create the folder if the relocation folder of the file doesn't exist
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.

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

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.

So this is what I did ...
New -> Java Project
(options: click "use project folder as root for sources and class files")
Next
Select "Link additional source" (under Details)
Browse "Linked folder location" and select the top folder (containing all your packages etc.)
Finish
If you already have a Project created then ...
Right-click on project in package explorer and select Properties
Select "Java Build Path"
Select "Link Source" (on the Source tab)
Browse "Linked folder location" and select the top folder (containing all your packages etc.)
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());
}
}
}

Related

How to export Intellij project as Eclipse archived folder

My professor wants all assignments submitted as an archived folder and wants the program to be able to run on his Eclipse when he grades them. The program is a simple one with one folder that has to contain just one class with the main method.
I am using IntelliJ.
I followed Jetbrains faq on exporting files as Eclipse-compatible using Files --> Export : https://www.jetbrains.com/help/idea/exporting-an-intellij-idea-project-to-eclipse.html
It looks like the files were successfully converted as my folder directory looks similar to what the website. A screenshot of my directory after exporting: https://imgur.com/a/qQY4lUH
I am not sure what to do here as I am not familiar with the Eclipse ".classpath" and ".project" files that were created as well as the .eml and .iml files. I don't know what to do with them.
I was thinking of just copying them into a new folder called "ReviewNW" and archiving them and submitting that folder. I don't know if that would be enough for Eclipse to run my program. Is there something else I have to do from here?
Additional question: I have since changed some things in my program. Now when I try to use File --> Export, IntelliJ gives me an error and says I "cannot export files already exported to eclipse-compatible format". What if I make some changes to my class files in my src folder and need to export those changes again? I think I would need to manually delete each of those Eclipse files and export again or is there a simpler way?
Thank you!

ImageJ: Debug with bioformats

I have downloaded imageJ source and imported into Eclipse. At the moment, I'm working on a plugin for imageJ and I can run imageJ with my plugin from eclipse and debug if I want. My problem is that I wish to init imageJ from eclipse but with the bioformats reader plugin loaded so I could open .lif files. How can I introduce this plugin into the imageJ source code? I have tried to add dependecies to the .jar file of bioformats in my project but it doesn't work.
Do not copy around source files, nor JAR files. You should manage your project dependencies using Maven or similar 21st century build tool (Gradle is also effective). Add a dependency on net.imagej:ij and ome:formats-gpl and maybe other Bio-Formats artifacts, as you need.
See also:
The Development page of the ImageJ wiki.
The minimal-ij1-plugin example
Just for who ever is looking at the same problem:
Download all the source code: https://github.com/openmicroscopy/bioformats
Copy the folder: bioformats-develop\components\bio-formats-plugins\src to your project.
Copy loci.plugins.LociImporter.java to ij.plugin.
Delete loci.plugins.LociImporter.java
Modify ij.plugin.LociImporter.java and add the line of arg:
public void run(String arg) {
DebugTools.enableLogging("INFO");
arg = "location=[Local machine] windowless=false "; //<-This one
[...]
}
Modify loci.plugins.in.Importer.java:
//import loci.plugins.LociImporter;//substitute this import per
import ij.plugin.LociImporter;//this one
Modify ij.Menus.java:
[...]
Menu importMenu = getMenu("File>Import", true);
addPlugInItem(importMenu, "Bio-Formats", "ij.plugin.LociImporter",0,false); //<-Add this line
[...]
Add bioformats.jar as an external lib to the project.
Run the project. Now you can open .lif from file->import->Bio-Formats. With this modification you won't be able to do drag and drop but you will be able to use this plugin just opening files with this menu. As this is only using the "import" this is only useful for opening. If you want something about saving, you should call loci.plugins.LociExporter("") in the same way I did for the import. (actually with my modification we are calling ij.plugin.LociImporter("location=[Local machine] windowless=false ")

How do you configure eclipse to work with a project that wasn't created by it (java)

I have been using the text editor gedit and the terminal for my latest project but I find that I have so many classes it would be more useful to be working with a separate directory for my .class and .java files so I can see what is going on more easily.
Unfortunately I have not been able to figure out how to get eclipse to work with a project that has already been made (or even one that was already made on eclipse with another computer!). This was not such a problem with two or three classes but I am getting to have so many that it is really tedious- It seems to want me to build a completely new project or nothing.
EDIT (additional info):
I don't think it will be possible to show the code of the project as I current have 12 classes for it but by the end I may have one or two more...
I know how to make a project in eclipse. What I am not sure how to do it open a directory full of .java files in eclipse that were created using a text editor rather than in an eclipse project and get eclipse to accept it as a project.
Does anybody know how to achieve this task?
You can import your project into eclipse doing the following steps:
Create a new Java Project in Eclipse (By going to File -> New -> Java Project) select a name for the project and you can select finish
You have to import your existing code to eclipse, go to:
File -> Import -> General -> FileSystem
Then browse to the directory where your code is currently, and say you want to import into the project you created in step 1
Afterwards remember to go to the project properties (right click in the project folder while in the navigator view, for example) and make sure the java build path has the right source folders configured.
Fortunately, you can use eclipse for any project previously created. Do you possibly have the code to show us how you are applying to the project in eclipse?
For example, you can create a project and class, then copy over starting from public static void main(String[] args) {
down to the bottom, then import the important stuff above the main class name.

Hadoop Create your own program

I am new toy Hadoop and i am wondering how to write a program in Netbeans.
The whole idea is to take the source code of word count and then write a new program. The steps i followed are those:
In Netbeans i created a new Class . (SplitData).
Copy- Pasted the entire code of word count and then renamed the class name.
But i have problems in Netbeans. It cannot find the imports.
Hmm, I assumed that you created already the project and then add your SplitData class. In the project tab(in default on your left) you have your created project. Expand it and right-click on the "Librabies" -> "Add JAR/Folder..." and then find the hadoop jar file(in linux a default location /usr/lib/hadoop/hadoop.jar). That's it.

Help me understand Eclipse's Java Build Path

I have been moving my Java projects from Jdeveloper over to Eclipse whenever I have to go back and make a change (I only work with Java projects sparingly).
Everytime I try to create a project in Eclipse (3.3.2) I spend quite some time trying to figure out the proper way to configure the source directories in the Java build path dialog.
The biggest problem I'm having is getting the source directories to match up with the package specified in the source files. For Example my project looks like this:
MyProject
DevelopmentBuilds
MainSRC
The MainSRC directory is also the "Root" package so my classes would be defined as:
package MainSRC.Sub1;
If I set my included directory to blank, the files compile but with many errors because the Packages are not in the right place.
How do I tell eclipse to start at MainSRC for the compilation rather than the children of MainSRC?
Or, should I the path up with one src folder with MainSRC as subfolder?
I basically don't understand how this works.
you need to set MainSRC as a 'Source Folder'.
Apparently, you project root are set as Source Folder.
Enter in project properties:
. Right click over your Project root, and select Properties
. Choose Java Build Path
. Remove all source folders
. Click 'Add Folder'
. Select 'MainSRC'
. Click Ok and Ok
Now, your MainSRC are a Source Folder. Some error occurs inside source files. For agile process, right click over package 'Sub1', and press F2. Rename your package for a new, then all your source files will be put in the correct new package.
[]'s,
And Past
You would need to set the source directory to the root MyProject directory. You would have to tell Eclipse to exclude the other directories (such as DevelopmentBuilds) as they are not source code.
You might find you're better off conforming to Eclipse's expectations and creating a source folder which contains your main package folder.