I've just imported a large amount of source code into Eclipse and basically the package name is no longer valid (the code has been moved folders). Is there a way to select all the source code in the Package Explorer and hit a hotkey so that all package declarations are correctly resolved for me? I know you can do this with imports by selecting the source and hitting ctl-shift-o, but is also possible for the package declaration?
Update: Refactoring the packages doesn't work as I don't want to change the name or location of the packages, I just need to adjust the package declaration in the Java source code.
If the package declarations are no longer valid, then all such invalid declarations would appear in the Problems view in Eclipse. If you do not see this view, you can open it from Window-> Show View -> Other... -> Problems (under the General tab).
You can filter on problems in the Problems view and correct easily correctable ones, by choosing the Quick fix option in the context menu (available on a right-click). In your case you should see something similar to the screenshot posted below:
Applying the quick fix options is trivial, as long as you know which one is correct - you would either have to change the package declaration in the class, or the location of the class itself. Unfortunately there is no option to fix the issue across multiple units at one go; you will have to apply the quick fix for every problem.
If you want to filter on problems of only this variety, consider configuring the Problems view to show all errors that have the text content "does not match the expected package" in the error text, as demonstrated in the following screenshots:
For this particular problem (which usually comes with auto generated artifact files), I found a neat solution.
So if the issue is that your package declarations is "package abc;" in 200 files, and you want it to be "package com.aa.bb.cc.abc;"
Then in eclipse, Search->File for "package abc;" in required folder or pkg or whole workspace. Don't select Search option but select "Replace" and then put "package com.aa.bb.cc.abc;" when it asks for the replacement after search.
Should do the trick.
Right click on the package, select Refactor > Rename. This will update all source files with the new package name.
I just had the same problem so I wrote a bash script to do it.
function java-package-update {
for path in $(find $1 -type f -name "*.java"); do
D=$(dirname $path);
F=$(basename $path);
P=$(echo $D|tr '/' '.');
if egrep -q '^\s*package\s*' $path; then
sed -i '' '/^\s*package\s*/s/^\(\s*package\s*\)[^;]*\(;.*\)/\1 '$P'\2/' $path;
else
echo >&2 "no package in $path";
fi;
done;
}
The sed command used is the one on OSX. If you're using gnu sed, then you don't need the '' paramater after the -i.
Just paste it in and run it on the directory containing your source. Backup your source first unless you're very brave.
Example:
$ cd /home/me/proj/fred/src
$ ls
com
$ cp -a com com.backup
$ java-package-update com
$ # fingers crossed
$ diff -ru com.backup com
I really should start doing this stuff in a more modern language like perl :)
This should do the trick for you.
Import all your files into the default package first and then drag them into
the new package, JDT will do the refactoring and change the package declarations across the project.
It is an old question, but I ran into the same problem and wrote a very simple bash script. Hope it will help someone.
for i in *.java; do
sed -i 's/.*package com.example.something;.*/package com.example.something_else;/' $i
done
Basically, the script traverses all java files inside a directory, and each occurrence of package com.example.something; replaces with package com.example.something_else;.
ALT+SHIFT+R add underscore at end of package name, hit ENTER twice
ALT+SHIFT+R delete the underscore, ENTER twice
Done if there are few packages.
Related
So I'm completely new to programming, and I've been writing some Java with the NetBeans IDE. My code runs fine within NetBeans, but I've tried to run it using the command line as well. However, if I run it from the command line, I have to delete the line:
package firstprogram;
which NetBeans automatically places at the top of each new file, or I get the error:
Error: Could not find or load main class FirstProgram
However, if I do delete the line, then the program no longer runs within NetBeans! It doesn't seem right that I have to choose whether to run a .java from within NetBeans or without.
The research I've done makes me think that this is something to do with directory structure? But everything I read on that goes straight over my head. NetBeans has a structure with "build", "dist", "nbproject", and "src", but when I use the command line I just place the .java file in an empty directory and javac from there.
Any explanation is appreciated! The books and tutorials I'm learning from either assume you're just using NetBeans or don't have the package line at all.
You can compile your class using javac command from anywhere, as long as you provide correct relative or absolute path. The problems come when you want to run your program using the java program.
You have to provide the correct path corresponding to your package declaration. For example, if I had 'MyClass' in package mypackage, first line would look like this:
package mypackage;
class source stored on disk:
c:/MyNetbeansProject/src/mypackage/MyClass.java
Compiled bytecode:
c:/MyNetbeansProject/build/classes/mypackage/MyClass.class
Now, if I would have opened a command prompt/terminal in folder c:/MyNetbeansProject/build/classes/, I could run the program using java mypackage/MyClass or java mypackage.MyClass.
However, if i would be somewhere else, I would have to say where the class files are located using the cp option: java -cp c:/MyNetbeansProject/build/classes mypackage/MyClass. The path in cp option can be relative or absolute, use "" when it contains spaces.
Package are directory architecture.
If your class is in the package com.acme.test, the class should be in the com/acme/test directory.
Instead of placing your class in an empty folder, place it in a folder named firstprogram and do javac firstprogram/youclass.java
The package (and folder) permit you to arrange your architecture with logical pattern.
More info here : http://www.tutorialspoint.com/java/java_packages.htm
So like OcterA said, you should keep organized, but with only one class this is not the issue. I believe that your problem is that you are not entering the correct command into the command line.
First cd to the correct directory and when you want to execute a file within a package in that directory you need to enter
java packageName.className
In this case
java firstprogram.FirstProgram
Is there a feature in netbeans that'll let me easily config and replace all occurrences of "system.out" and "e.printstacktrace" to "logger.info/error/log" ?
I used find/replace to get rid of all the "system.out"s, and now i need to get rid of all the "printstacktraces", I can probably write a parser and read all my java files. But before I do that I just want to know if something like this is already implemented in netbeans, currently in netbeans 7.1 hints, they only show you where these things are, but I couldn't find an option for code refactoring.
Thanks
The following will open each .java file that contains printStackTrace in vim.
Of course you can substitute vim with your text editor of choice:
alias javafind='find . -name '\''*.java'\'' -print | xargs fgrep -il'
vim `javafind printStackTrace`
The first command creates an alias that returns all java files (starting in the current directory) that contain the first argument.
The second command says: open each file that contains the term printStackTrace with vim.
An even better solution would be to use sed to intelligently search/replace with a regex.
I have Windows 7, installed jdk1.7.0 and its supporting jre7.
My problem is compilation part works perfectly, but while running the Java program I get this error saying:
"Could not find or load main class"
I am storing all my programs in javalab folder. I have set the path to it. Procedure looks like this:
C:\Users\user>cd\
C:\>cd javalab
C:\javalab>autoexec.bat
C:\javalab>set path=C:\Program Files\Java\jdk1.7.0\bin
C:\javalab>javac p1.java
C:\javalab>java p1
Error: Could not find or load main class p1
C:\javalab>
I was having a similar issue with my very first java program.
I was issuing this command
java HelloWorld.class
Which resulted in the same error.
Turns out you need to exclude the .class
java HelloWorld
Try:
java -cp . p1
This worked for me when I had the same problem, using Fedora (linux)
Simple way to compile and execute java file.(HelloWorld.java doesn't includes any package)
set path="C:\Program Files (x86)\Java\jdk1.7.0_45\bin"
javac "HelloWorld.java"
java -cp . HelloWorld
pause
javac should know where to search for classes. Try this:
javac -cp . p1.java
You shouldn't need to specify classpath. Are you sure the file p1.java exists?
I had almost the same problem, but with the following variation:
I've imported a ready-to-use maven project into Eclipse IDE from PC1 (project was working there perfectly) to another PC2
when was trying to run the project on PC 2 got the same error "Could not find or load main class"
I've checked PATH variable (it had many values in my case) and added JAVA_HOME variable (in my case it was JAVA_HOME = C:\Program Files\Java\jdk1.7.0_03)
After restarting Ecplise it still didn't work
I've tried to run simple HelloWorld.java on PC2 (in another project) - it worked
So I've added HelloWorld class to the imported recently project, executed it there and - huh - my main class in that project started to run normally also.
That's quite odd behavour, I cannot completely understand it.
Hope It'll help somebody. too.
i guess that you have a different class name in p1.java
Check you class name first. It should be p1 as per your batch file instruction. And then check you package of that class, if it is inside any package, specify when you run.
If package is x.y
java x.y.p1
Here is my working env path variables after much troubleshooting
CLASSPATH
.;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
PATH <---sometimes this PATH fills up with too many paths and you can't add a path(which was my case!)
bunchofpaths;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
Additionally, when you try to use the cmd to execute the file...make sure your in the local directory as the file your trying to execute (which you did.)
Just a little checklist for people that have this problem still.
I've had similar problems. If you work with Eclipse, you need to go to the folder where you have your src/ folder... If you used a package - then you use
javac -cp . packageName/className
which means if you've had a package named def and main class with name TextFrame.java you'd write
javac -cp . def/TextFrame
omitting the trailing .java extension, and then you run it with the
java def/TextFrame
and if you have have arguments, then you need to supply it with arguments corresponding to your program.
I hope this helps a bit.
First, put your file *.class (e.g Hello.class) into 1 folder (e.g C:\java). Then you try command and type cd /d C:\java. Now you can type "java Hello" !
You might have the CLASSPATH environment variable already added!!
Use following to avoid further usage of -cp . in java -cp . CLASSFILE
Add . to CLASSPATH in system properties->environment variables or by cmd
set CLASSPATH=%CLASSPATH%;.;
I faced a similar problem in Eclipse. Whenever I clicked on the Run button it gave me the message, "Error: Could not find or load main class". But when I right click on the java file in the project explorer and Run As Java configuration, it works perfectly.
I think this is because it tries by default to run it in some other configuration which causes problems.
Hope this answer helps some.
If you have a single .java file to compile using command-line , then remove
topmost package parts from the code, the compile again, it will work.
This worked for me.
Sometimes what might be causing the issue has nothing to do with the main class. I had to find this out the hard way, it was a referenced library that I moved and it gave me the:
Could not find or load main class xxx Linux
I just delete that reference and added again and it worked fine again.
i had
':'
in my project name e.g 'HKUSTx:part-2'
renaming it 'HKUSTx-part-2' worked for me
You can use NetBeans IDE which is free to download and use "Open Source". You can even do other programming language in this IDE. The latest of which it supports HTML5. This makes your programming easier. If you're not familiar with it choose a book that is NetBeans integrated like Sams Teach Yourself Java in 24 Hours
I am joining a competition that requires me to put all my java classes in one single .java file. Does there exist a tool that does this for me (including changing the visibility of classes to be able to do this)?
Addition: thanks for trying to help me to read the site of the competition but I quote:
It is possible to make more than one
class for your program, but you will
have to put the source for all classes
in a single .java file (the compiler
will produce multiple .class files
anyway). When you do this, you should
not declare your classes public, or
the compiler will complain about it.
So, only 1 .java file is allowed (no jar) and in that file I can have multiple non-public classes besides my public main class (and not only static inner classes as suggested).
If you have access to Unix-y shell (for Windows, you can install e.g. Git for a decent Bash implementation, and it gives you a great VC tool):
cat *.java | sed 's/public class/class/g' >AllTehCodez.java
Doesn't have to be more complicated than that (unless you have a lot of strings containing the substring "public class", of course).
Edit: Doesn't work for package and imports. But...
(
egrep -h ^package *.java | head -1
egrep -h ^import *.java | sort -u
egrep -hv '^(import|package)' *.java | sed 's/public class/class/g'
) >AllTehCodez.java
This does of course assume all the classes are in the same package.
If we exclude various "bijou scripting haquettes" along the lines suggested above, I seriously doubt that any serious tool exists for doing this.
Why? Because this kind of nonsense goes against all known Java style rules and conventions!
The people behind that website need to be taught about archive file formats; e.g. TAR, ZIP, JAR.
EDIT
I take that back. They DO understand JAR files. Quoting from one of their documents:
Using your own executable Java jar with Caia
You can also use your own Java jar in
Caia competitions. We have written the
jarwrapper for that. The source of
jarwrapper.c is put in the
caia_install_/jarwrapper/
folder. In the Windows distro this is
put into the src/ folder.
Suppose the name of your class file is
JavaPlayer.class. The only thing you
will have to do is to rename the
executable in the bin/ folder from
jarwrapper to JavaPlayer. The
executable now will perform the
command: java -jar JavaPlayer. The jar
file should contain a manifest which
points to the class with the main
method.
In manager.txt you can use the program
name JavaPlayer which refers to the
executable that starts your Java jar
player.
The project I'm working on has about 10 jar files as libraries. At the top of one of the files there's an import statement like:
import jpe.nar.crat.maker.ObjectMakerFactory;
Is there a way to tell which Jar file it comes from?
(I'm using Netbeans if that matters.)
You can use CodeSource#getLocation() for this. The CodeSource is available by ProtectionDomain#getCodeSource(). The ProtectionDomain in turn is available by Class#getProtectionDomain().
URL location = ObjectMakerFactory.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getPath());
// ...
Have you tried doing a 'Open Declaration' on the class? In Eclipse, when you do it, it opens a window that shows the name of the jar and tells you that this jar has 'No Source Attachment'. I am hoping something similar should happen for NetBeans.
Thanks,
R
I like JFind very much:
http://jfind.sourceforge.net/
... it works recursively by looking into jar's, inside war's, inside ear's, etc...
If you wrap the java launcher in a shell script and put that on your PATH, it becomes a very powerful tool:
I.e. to find all EntityManager classes in directory jboss-6.0.0.20100429-M3 :
$ jfind.sh EntityManager ./jboss-6.0.0.20100429-M3
Search String: EntityManager
Windows Search Location: jboss-6.0.0.20100429-M3
....jjj.jjjjjjjjjjj
ClassName = javax/persistence/EntityManager.class
JarName = jboss-6.0.0.20100429-M3\client\hibernate-jpa-2.0-api.jar
----------------
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
ClassName = org/apache/xerces/impl/XMLEntityManager.class
JarName = jboss-6.0.0.20100429-M3\client\xercesImpl.jar
----------------
A little shell wrapper for use in Cygwin:
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` <classname> [<fromDir>]"
exit 1
fi
echo Search String: $1
SEARCH_LOCATION=`cygpath -w $2`
echo Windows Search Location: $SEARCH_LOCATION
java -jar `cygpath -w $HOME/bin/JFind.jar` "$1" "$SEARCH_LOCATION"
echo
In the Netbeans IDE:
In your code, ctrl-select the class name. After the relevant java file comes up in the editor (if you don't have source for the class, it might not show much). Right-click anywhere in the source window and select "Select In Projects". The class will show highlighted in the jar where it came from.
This has been working at least as far back as Netbeans 8.0.
You can use the Jar Class Search for netbeans. I'm not sure that it still compatible, but it's worth the try.
Programmaticly or interactively?
You can try DocJar. In Eclipse control click on the item will show you (the edit panel will show the source (if attached) or the methods available while Package Explorer will open the tree to the class), I would be surprised if Netbeans did not behave in a similar manor.
A former colleague of mine, Tom, wrote JarSniffer (http://sourceforge.net/projects/jarsniffer/). It's a handy little tool to find a class in a set of jars, zips and directory trees.
In Eclipse just do Ctrl-Click on the class name (in import sentence), then Right- Click on .class code, to open a dialog,·and finally chose Declarations-project.