- [Solved] Error: Could not find or load main class
- IntelliJ IDEA – Solution 1
- IntelliJ IDEA – Solution 2
- IntelliJ IDEA – Solution 3
- Eclipse – Solution 1
- Eclipse – Solution 2
- Eclipse – Solution 3
- Command Line – Solution 1
- Command Line – Solution 2
- Java error can you run it
- Причины ошибки с запуском Java
- Тут есть ряд причин, которые не дают правильной работе приложения:
- Исправление ошибки Unable to launch the application
- Популярные Похожие записи:
[Solved] Error: Could not find or load main class
If you are getting Error: Could not find or load main class error, it means JVM is trying to load a class with main method. Simply, JVM cannot find this class in the classpath.
main method
main() method has a special meaning in Java, it is the entry point of Java programs.
public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World"); > >
When you run the following command, it starts JVM, loads HelloWorld class and starts running its main method.
We will go through several possible reasons for this error. We usually use IDEs for software development, so first let’s examine how to fix this problem in our IDEs.
IntelliJ IDEA – Solution 1
If you run a main class through you IDE, it will be stored in Run/debug Configurations. You can easily run the class again with the run/debug buttons at a later time.
You might want to change the name of your class (Main -> Main2). If you update a class name on your IntelliJ, all references to this class will also be updated (including Run/debug Configurations). However, if you change a class name (or change its package) outside your IDE, Run/debug Configurations will become obsolete.
I renamed Main.java to Main2.java outside Intellij IDE and tried to run the code again using Run button. Now, it gives the following error message in console.
C:\Java.jdks\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 211.6556.6\lib\idea_rt.jar=14581:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 211.6556.6\bin" -Dfile.encoding=UTF-8 -classpath C:\abcstudyguide\codes\out\production\Main com.abc.Main Error: Could not find or load main class com.abc.Main Caused by: java.lang.ClassNotFoundException: com.abc.Main Process finished with exit code 1
You can update Run/debug Configurations to fix the error.
IntelliJ IDEA – Solution 2
Sometimes just rebuilding your project is enough to resolve this error. To rebuild the project, select Build -> Rebuild Project.
IntelliJ IDEA – Solution 3
If there is some residue left in the cache, you can invalidate caches and restart you IDE.
Eclipse – Solution 1
Similar to IntelliJ, you can run Java application in eclipse.
Once you run your application, it is saved as a Run Configuration. If you update your application main class outside Eclipse IDE and try to run it again, you will get Error: Could not find or load main class error message.
If you have updated class name or package outside Eclipse IDE, you need to update Run Configurations accordingly.
Eclipse – Solution 2
If there is nothing wrong with your Run Configurations, you can try to clean and build your project. Note that Build Automatically option is selected.
Eclipse – Solution 3
If you copied the project from another computer, your build path might be pointing incorrect path. To check the build path of your project, select File -> Properties from menu and open Java Build Path.
Eclipse warns you with message: Build path entry is missing: C:/jar_libs/jdbc.jar. To fix the path of jar file, click on Edit button and update with correct path.
Command Line – Solution 1
You can also use command line to compile and run your Java programs. Consider the following HelloWorld class. It is a simple class with a main method. There is no package declaration in the source code.
You can compile your source code with javac command and run the compiled code with java command. There are a few things you need to pay attention to while running the code.
Java is case-sensitive, so you should type your class name exactly the same. If you type helloworld instead of HelloWorld, command will give error.
Also, file extensions (like HelloWorld.class) should not be used when running java command.
C:\codes>javac HelloWorld.java C:\codes>java HelloWorld Hello World! C:\codes>java helloworld Error: Could not find or load main class helloworld C:\codes>java HelloWorld.class Error: Could not find or load main class HelloWorld.class
Command Line – Solution 2
Following code is similar to previous one, but in this example HelloWorld class is defined under a package. In Java, packages are used to organize similar classes together.
Packages are organized as directories on your file system. For instance, HelloWorld class is created under com.abc.study.guide package, so HelloWorld.java file should be in /com/abc/study/guide folder.
package com.abc.study.guide; public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World!"); >>
To run a class, we are using FQN (Fully Qualified Name) of the class – that is (package.class name). For HelloWorld class in our example FQN is com.abc.study.guide.HelloWorld. Thus, java comand to run this class is: java com.abc.study.guide.HelloWorld .
C:\codes>javac com\abc\study\guide\HelloWorld.java C:\codes>java HelloWorld Error: Could not find or load main class HelloWorld C:\codes>java com.abc.study.guide.HelloWorld Hello World!
You can run HelloWorld class from any directory in file system. But if you are running java command from outside the project root directory, classpath parameter should be used. Classpath tells JVM where to look for classes – it’s path of classes. You can specify the class path is by using the -classpath (or -cp) command line switch.
C:\another-directory>java com.abc.study.guide.HelloWorld Error: Could not find or load main class com.abc.study.guide.HelloWorld C:\another-directory>java -classpath C:\codes com.abc.study.guide.HelloWorld Hello World! C:\another-directory>java -cp C:\codes com.abc.study.guide.HelloWorld Hello World! C:\codes\com\abc\study\guide>java com.abc.study.guide.HelloWorld Error: Could not find or load main class com.abc.study.guide.HelloWorld C:\codes\com\abc\study\guide>java -cp ../../../.. com.abc.study.guide.HelloWorld Hello World!
Java error can you run it
Добрый день! Уважаемые читатели и гости компьютерного блога №1 в России Pyatilistnik.org. Я уверен, что у многие системные администраторы используют в своей практике, порты управления серверами, про которые я уже очень подробно рассказывал. Если вы новичок в этом деле, то это отдельный сетевой интерфейс, который позволяет взаимодействовать с сервером, не имея на нем операционной системы. Самый используемый случай, это если завис сервер, чтобы его дернуть, или для того, чтобы установить на нем удаленно ОС. Благодаря такому KVM, вы монтируете в него ISO, эмулируя DVD-rom, а дальше все стандартно. Есть единственный минус, данный KVM работает на Java, которое очень привередливое и очень часто глючит. У меня есть старенькие лезвия Dell M600, и вот при попытке открыть IDRAC, я получаю ошибку Unable to launch the application, что не дает запуститься консоли квм. Данная ошибка, очень часто встречается в клиент-банках, которые так же могут работать через Java. Ниже я покажу как ее исправить и решить на корню.
Причины ошибки с запуском Java
Вот так вот выглядит ошибка:
Unable to launch the application. Если посмотреть вкладку Details, то тут можно будет найти такую ошибку: Unsigned application requesting unrestricted accses to system. The following resourse is signed with a weak signature algorithm MD5withRSA and is treated as unsigned: https://ip адрес/Applications/dellUI/Java/release/JViewer.jar
Тут есть ряд причин, которые не дают правильной работе приложения:
Исправление ошибки Unable to launch the application
Первым делом вам необходимо поправить один конфигурационный файл, под именем java.security. Данный файл располагается по пути C:\Program Files\Java\ваша версия java\lib\security\java.security. Перед его редактированием советую сделать его резервную копию.
Открываем его с помощью блокнота или Notepad++ и находим строку:
Перезапустите браузер. Если это не помогло исправить ошибку: Unsigned application requesting unrestricted accses to system, то сделаем еще вот, что. Так как JAVA имеет очень высокий риск хакерской атаки, то разработчики задали там очень высокий уровень безопасности. Чтобы он не срабатывал, на нужных нам ресурсах, нам необходимо добавить адрес в исключения.
Советую добавлять в исключения адреса со *, например, https://192.168.0.1/*, так как этот знак означает любые последующие знаки. Или вот еще пример https://*.ibm.com
Напоминаю, что подобное мы уже делали, при ошибке: Java Application Blocked. Открываем панель управления Windows, находим там значок Java. Открываем его и попадаем в Java Control Panel. Переходим на вкладку «Security». Оставьте уровень защиты на «High», чуть ниже будет пункт список сайтов для исключения «Exception Site List», по умолчанию он будет пустым. Для его редактирования нажмите кнопку «Edit Site List». Для добавления новой строки нажмите кнопку «Add» и введите нужный вам ресурс. Сохраняем настройки и перезапускаем браузер.
В итоге это в 100% случаев решает ошибку с запуском окна на Java. В итоге открыв KVM окно в IDRAC на Dell M600 я не увидел Unable to launch the application. В итоге Java-аплет запустился, попросил подтверждения того, что я доверяю данному издателю приложения. Чтобы оно больше не выскакивало, поставьте галку «Do not show this again for this app from the publisher above» и нажмите «Run» для запуска.
Мы почти у финишной прямой, но видимо судьба решила меня еще подразнить и я получил следующее сообщение:
В Internet Explore: Failed to establish connection with VKVM service for video redirection.
В Google Chrome: Unable to find certificate in Default Keystore for validation. Please upload the certificate using the Java Control Panel and try again. Java Control Panel can be found at the following locations.
Мой сертификат на лезвии Dell M600, закончился в 2012 году и был выпущен компанией делл, у меня два варианты, забить на это и сделать следующие шаги, либо же сгенерировать csr запрос и отправить его деловцам, чтобы те дали новый сертификат, что геморройно, либо обновить IDRAC, но вся загвоздка в том, что оборудование Dell M600 уже снято с поддержки и порт управления имеет последнюю прошивку.
Что делаем далее, удаляем из хранилища Java текущий сертификат, делается это через все тот же Java Control Panel, на вкладке «Security» в пункте «Manage Certificates»
Находим нужный сертификат и удаляем его.
Далее как в случае с ошибкой » Failed to validate certificate. The application will not be executed» нам необходимо почистить кэш в джаве. Делается это на вкладке общие «General», через кнопку настроек «Settings». Далее нажимаем «Удалить файлы (Delete Files)»
Перезапускаем браузер и пробуем запустить ваше приложение. В итоге меня ждала уже следующая ошибка, которую я видел:
Надеюсь вы смогли решить вашу проблему с запуском java-приложения и победили ошибку: Unable to launch the application. Unsigned application requesting unrestricted accses to system. The following resourse is signed with a weak signature algorithm MD5withRSA and is treated as unsigned. Если у вас есть другие методы, то просьба описать их в комментариях, давайте делиться опытом.
Популярные Похожие записи:
Приложению Excel не удалось вставить данные, 100% решение
Smata.Ru сервер лицензий недоступен
- Настройка #unsafely-treat-insecure-origin-as-secure в Chrome и Edge
Ошибка 0x00002740: only one usage of each socket address
Ошибка DCOM ID 10036, решаем за минуту
- Ошибка ID 513 CAPI2, решаем за минуту