Меню

Ошибка java virtual machine launcher error a jni error has occurred please

При запуске какого-либо кода, написанного на Java, программист может получить сообщение об ошибке с текстом «A JNI error has occurred, please check your installation and try again». Обычно причиной ошибки выступает разница в версии компилятора и среды выполнения, из-за чего происходит некорректная интерпретация и выполнение имеющегося кода. Ниже разберём, в чём суть данной ошибки, как её исправить, а также отдельно укажем, как решить данную ошибку при запуске игры Minecraft.

  • Что такое JVM, JNI и JRE?
  • Причина проблемы A JNI error has occurred, please check your installation and try again
  • Установите одинаковую версию JRE и JDK
  • Правильно настройте переменные среды для Java
  • Ошибка JNI error has occurred при запуске Майнкрафт
  • Заключение

Что такое JVM, JNI и JRE?

Как известно, программы, написанные на «Java», компилируются в байтовый код, который распознаётся виртуальной машиной Ява, называемой «JVM» (Java Virtual Machine). JVM по своей сути является компьютерным симулятором, и при запуске программы написанной на Java, распознаёт инструкции байтового кода, и переводит их в машинные инструкции собственной системы.

JVM должна обеспечивать удобный способ доступа к ресурсам системы – файлам, сетевым соединениям, видеокарте и другим компонентам. Механизмы доступа к этим ресурсам напрямую зависят от системы, в которой работает JVM. Для обеспечения своей работы виртуальная машина использует собственный интерфейс Java, называемый «JNI» (Java Native Interface).

Методы Java, использующие JNI для доступа к службам, квалифицируются термином «native». Квалификатор «native» сообщает виртуальной машине, что код для выполнения при вызове данного метода присутствует во внешней библиотеке. JVM ищет конкретный вызов библиотеки, который необходимо выполнить, на основе полного имени пути к методу и его аргументам. Существует специальное соглашение об именах, позволяющее сопоставить метод с конкретной ссылкой на внешнюю библиотеку.

Данный механизм JNI позволяет программам на Java кодировать имя переносимого метода. И скомпилированный в Виндовс код Java будет отлично запускаться на компьютерах под управлением Линукс или Мак.

Как мы уже писали выше, Java имеет собственные библиотеки для обеспечения базового взаимодействия с системой на уровне чтения-записи файлов, создания сетевых подключений и вывода изображения на экран. Они распространяются с JVM как часть среды выполнения Ява, известные как «JRE» (Java Runtime Environment), независимо от того, является ли она автономной JRE или включена в Java Development Kit (JDK).

Причина проблемы A JNI error has occurred, please check your installation and try again

Текст данной ошибки переводится как «Произошла ошибки INI, пожалуйста, проверьте вашу инсталляцию и попробуйте вновь». Данная ошибка, получаемая при запуске программы на JVM, указывает на проблему с запуском кода, связанного с собственным методом.

Причины проблемы могут быть следующими:

  • Повреждена библиотека JDK / JRE, вследствие чего она не может быть загружена, и JVM не сможет выполнить код;
  • Повреждён функционал операционной системы, вследствие чего последняя не в состоянии удовлетворить системный вызов, созданный нативным кодом;
  • Имеются различия в номерах версий JRE (среда выполнения Java) и JDK (Java Development Kit), что также может вызывать ошибку JNI. Различия в номерах версий приведут к тому, что JVM откажется запускать код, потому что он был скомпилирован для совместимости с версией Java, превышающей максимальную версию, поддерживаемую JVM. Проще говоря, код может быть скомпилирован на одной версии Ява (например, 10), а пытается запускаться с помощью версии Ява 9;
  • Также проблема может быть вызвана при попытке запустить файл.jar через командную строку, например с помощью команды java -jar File.jar.

Давайте разберём способы, позволяющие устранить ошибку JNI на вашем ПК.

Это может помочь: ошибка Out of memory — как устранить.

Установите одинаковую версию JRE и JDK

Исправить ошибку «A JNI error has occurred» поможет обновление JRE и JDK до актуальных синхронных версий. Необходимо убедится в их одинаковой версии, для чего вызовите системную строку (нажмите Win+R, введите там cmd и нажмите ввод), и наберите там:

java -version и нажмите ввод.

Затем наберите: javac –version

Полученные результаты должны совпадать. Если они они не совпадают, то это сигнализирует о несоответствии версии компилятора и среды выполнения Java. Для решения проблемы рекомендуем установить однотипные и актуальные версии компилятора и среды выполнения, после чего вновь используйте команды «java -version» и «javac -version» для проверки, возвращают ли данные команды один и тот же номер версии.

Если версии синхронны, тогда ваш код Java необходимо будет скомпилировать с помощью компилятора новой версии. После этого ошибка «A JNI error has occurred, please check your installation» может быть устранена.

Правильно настройте переменные среды для Java

Для исправления ошибки «A JNI error has occurred» может понадобится настроить переменные среды для Java. Выполните следующее:

  1. Нажмите на Win+R;
  2. В открывшемся окошке введите sysdm.cpl и нажмите на ввод;
  3. Откроется окно свойств системы. Выберите вкладку «Дополнительно»;
  4. Далее внизу кликните на кнопку «Переменные среды»;
  5. В нижнем окне выберите переменную «Path», после чего нажмите чуть ниже на кнопку «Изменить»;
    Выберите «Path», и нажмите на «Изменить»
  6. Здесь вы ищите строку, в которой прописан путь установки вашего JDK. Например, он может хранится по пути C:ProgramFilesJavajdk-13.0.1bin;
  7. Если этой записи в перечне ваших переменных нет, вы можете добавить её, нажав на «Создать» справа. Если же вы еще не установили JDK, вы можете скачать её с https://www.oracle.com/java/technologies/downloads/;
  8. Когда вы найдёте данную строку, используйте кнопку «Вверх» пока запись не окажется в самой верхней части;
  9. Нажмите внизу на «Ок» для сохранения результата, и перезагрузите ваш ПК. Ошибка «JNI error has occurred» будет исправлена.

Смотрите на данном англоязычном виде способ решения возникшей проблемы:

Ошибка JNI error has occurred при запуске Майнкрафт

Некоторые пользователи, установившие обновление Minecraft 1.17 («Caves and Cliffs: Part 1»), сообщают, что получают сообщение об ошибке «A JNI error has occurred, please check your installation and try again» или «Java exception».

Если вы один из таких пользователей, тогда вам нет повода для беспокойства. «Ошибка JNI», которая начала появляться с последним обновлением Minecraft 1.17, может быть исправлена ​​путем установки Java 16 или более поздних версий для своей работы. Это подтверждается многими сообщениями от игроков, у которых возникла рассматриваемая в статье проблема.

Читайте также: GLFW error 65542: WGL the driver does not appear to support OpenGL – как решить?

Заключение

В нашем материале была рассмотрена суть ошибки «A JNI error has occurred, please check your installation and try again», и перечислены способы для её решения. Обычно причиной ошибки является несоответствие версии JRE и JDK, которые приводят к появлению рассматриваемой ошибки. Рекомендуем обновить версию данных инструментов до самой синхронной и актуальной, после чего декомпилировать ваш код. Обычно после этого ошибка будет устранена, и вы сможете использовать рабочую версию вашего кода для необходимых вам задач.

Содержание

  1. A JNI error has occurred, please check your installation and try again — как исправить?
  2. Что такое JVM, JNI и JRE?
  3. Причина проблемы A JNI error has occurred, please check your installation and try again
  4. Установите одинаковую версию JRE и JDK
  5. Правильно настройте переменные среды для Java
  6. “Error: A JNI error has occurred, please check your installation …” – How to fix it!
  7. JNI Error in Windows CMD
  8. JNI Error when starting a Minecraft Server
  9. JNI Error in Minecraft TLauncher
  10. Java JNI error message still appears?
  11. A JNI error has occurred, please check your installation and try again при компиляции java программы
  12. Как исправить ошибки при запуске и компиляции?
  13. Выводы
  14. Java virtual machine launcher jni error
  15. Breadcrumbs

A JNI error has occurred, please check your installation and try again — как исправить?

При запуске какого-либо кода, написанного на Java, программист может получить сообщение об ошибке с текстом «A JNI error has occurred, please check your installation and try again». Обычно причиной ошибки выступает разница в версии компилятора и среды выполнения, из-за чего происходит некорректная интерпретация и выполнение имеющегося кода. Ниже разберём, в чём суть данной ошибки, как её исправить, а также отдельно укажем, как решить данную ошибку при запуске игры Minecraft.

Что такое JVM, JNI и JRE?

Как известно, программы, написанные на «Java», компилируются в байтовый код, который распознаётся виртуальной машиной Ява, называемой «JVM» (Java Virtual Machine). JVM по своей сути является компьютерным симулятором, и при запуске программы написанной на Java, распознаёт инструкции байтового кода, и переводит их в машинные инструкции собственной системы.

JVM должна обеспечивать удобный способ доступа к ресурсам системы – файлам, сетевым соединениям, видеокарте и другим компонентам. Механизмы доступа к этим ресурсам напрямую зависят от системы, в которой работает JVM. Для обеспечения своей работы виртуальная машина использует собственный интерфейс Java, называемый «JNI» (Java Native Interface).

Методы Java, использующие JNI для доступа к службам, квалифицируются термином «native». Квалификатор «native» сообщает виртуальной машине, что код для выполнения при вызове данного метода присутствует во внешней библиотеке. JVM ищет конкретный вызов библиотеки, который необходимо выполнить, на основе полного имени пути к методу и его аргументам. Существует специальное соглашение об именах, позволяющее сопоставить метод с конкретной ссылкой на внешнюю библиотеку.

Данный механизм JNI позволяет программам на Java кодировать имя переносимого метода. И скомпилированный в Виндовс код Java будет отлично запускаться на компьютерах под управлением Линукс или Мак.

Как мы уже писали выше, Java имеет собственные библиотеки для обеспечения базового взаимодействия с системой на уровне чтения-записи файлов, создания сетевых подключений и вывода изображения на экран. Они распространяются с JVM как часть среды выполнения Ява, известные как «JRE» (Java Runtime Environment), независимо от того, является ли она автономной JRE или включена в Java Development Kit (JDK).

Причина проблемы A JNI error has occurred, please check your installation and try again

Текст данной ошибки переводится как «Произошла ошибки INI, пожалуйста, проверьте вашу инсталляцию и попробуйте вновь». Данная ошибка, получаемая при запуске программы на JVM, указывает на проблему с запуском кода, связанного с собственным методом.

Причины проблемы могут быть следующими:

  • Повреждена библиотека JDK / JRE, вследствие чего она не может быть загружена, и JVM не сможет выполнить код;
  • Повреждён функционал операционной системы, вследствие чего последняя не в состоянии удовлетворить системный вызов, созданный нативным кодом;
  • Имеются различия в номерах версий JRE (среда выполнения Java) и JDK (Java Development Kit), что также может вызывать ошибку JNI. Различия в номерах версий приведут к тому, что JVM откажется запускать код, потому что он был скомпилирован для совместимости с версией Java, превышающей максимальную версию, поддерживаемую JVM. Проще говоря, код может быть скомпилирован на одной версии Ява (например, 10), а пытается запускаться с помощью версии Ява 9;
  • Также проблема может быть вызвана при попытке запустить файл.jar через командную строку, например с помощью команды java -jar File.jar.

Давайте разберём способы, позволяющие устранить ошибку JNI на вашем ПК.

Установите одинаковую версию JRE и JDK

Исправить ошибку «A JNI error has occurred» поможет обновление JRE и JDK до актуальных синхронных версий. Необходимо убедится в их одинаковой версии, для чего вызовите системную строку (нажмите Win+R, введите там cmd и нажмите ввод), и наберите там:

java -version и нажмите ввод.

Затем наберите: javac –version

Полученные результаты должны совпадать. Если они они не совпадают, то это сигнализирует о несоответствии версии компилятора и среды выполнения Java. Для решения проблемы рекомендуем установить однотипные и актуальные версии компилятора и среды выполнения, после чего вновь используйте команды «java -version» и «javac -version» для проверки, возвращают ли данные команды один и тот же номер версии.

Если версии синхронны, тогда ваш код Java необходимо будет скомпилировать с помощью компилятора новой версии. После этого ошибка «A JNI error has occurred, please check your installation» может быть устранена.

Правильно настройте переменные среды для Java

Для исправления ошибки «A JNI error has occurred» может понадобится настроить переменные среды для Java. Выполните следующее:

Источник

“Error: A JNI error has occurred, please check your installation …” – How to fix it!

You have encountered this JNI Error error message? Don’t panic! The problem can usually be solved quite quickly – and here you can find out how.

Have you encountered this error message or popup?

Error: A JNI error has occurred, please check your installation and try again

The problem comes from the fact that your JRE (Java Runtime Enviroment), that is your installed Java version and your JDK (Java Development Kit) do not work together correctly. Advertisements

Now there are several possible solutions for you. Just choose the scenario that applies to you:

JNI Error in Windows CMD

The problem can occur if you want to call a .jar file via command line (Windows CMD), e.g. via the command java -jar File.jar or if you have compiled your program with Eclipse before.

To fix the error, you need to adjust the environment variables for Java.

  • To do this, type “environment variable” in your Windows search and open the “Edit System Environment Variables” item. In this window you click on “Environment variables…”.

System properties – screenshot

  • The “Environment variables” window opens. There you select the variable “Path” in the lower window “System variables” and click on “Edit…”.

Environment variables – screenshot

  • There you look for the line where the installation path of your Java JDK is stored. In my case this is under C:Program FilesJavajdk-13.0.1bin.

If you don’t have a Java JDK installed yet, you can download and install the .exe installation file (“x64 Installer”) here. Advertisements

  • If you do not have this entry, you can add it by clicking the “New” button.

Edit environment variables – screenshot

  • Select the line with the Java JDK and click on “Move up” until the entry is at the top. Done!
  • Now you have to close and reopen the Windows-CMD once and the error should be fixed.

JNI Error when starting a Minecraft Server

If you try to start your Minecraft server via the official server.jar (error occurs since version 1.17), you may get this error message:

  • Download the latest Java JDK version as .exe file (“x64 Installer”) and install by clicking on the .jar file
  • Now the server should start again

JNI Error in Minecraft TLauncher

This error message can also appear when launching the Minecraft TLauncher.

  • Download the latest Java JDK version as .zip archive (“x64 Compressed Archive”) (see screenshot)

Advertisements Java JDK Download Page

  • Right-click on the downloaded file and click “Extract here”.
  • Copy the unzipped folder to the directory C:Program FilesJava
  • Launch your Minecraft TLauncher and click on the gear in the bottom right corner
  • Click at “Java path” on “Browse…” and choose C:Program FilesJavajdkXbinjavaw.exe (replace the X by the name of your JDK folder).
  • Save everything – now the game should start again

Advertisements

Java JNI error message still appears?

  • Restart your computer
  • Uninstall old Java versions under Control Panel > Programs > Programs and Features and install the latest Java JRE and Java SDK.

I hope that you were able to fix the JNI error with the help of this post. If this is still not the case, feel free to write me a comment.

Источник

A JNI error has occurred, please check your installation and try again при компиляции java программы

Многие новички, которые изучают программирование на Java при компиляции могут столкнуться с ошибкой «A JNI error has occurred, please check your installation and try again». Ошибка выскакивает даже если запускать совсем простой код типа «hello world!» как в примере ниже.

Пример простого кода Hello World!

Обычно компиляция проходит, но созданный класс не интерпретируется. У большинства пользователей ошибка появляется из-за следующих двух моментов:

  1. Неправильные пути в переменных средах;
  2. Вы компилируете файл более новой версией Java, а запустить пытаетесь на более ранней. Например компилировали при помощи Java 10, а запускаете на Java 9.

Как исправить ошибки при запуске и компиляции?

Первое, что следует проверить – пути в переменных средах. По списку первым например стоит путь:

«C:Program Files (x86)Common FilesOracleJavajavapath»

А в конце каталог до jdk:

Операционная система компьютера находит екзешник «java.exe» и первым делом смотрит в «..javapath» и останавливает поиск. Вам нужен файл что лежит в «…jdkbin». В переменных средах сначала нужно поставить jdkbin, а потом уже javapath. В конечном результате путь должен быть примерно такой:

PATH=C:Program Filesjdkbin;C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:WindowsSystem32OpenSSH;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program Files (x86)QuickTimeQTSystem

Во втором случае всё еще проще. Если вы компилируете используя более позднюю версию Java Runtime 54, то соответственно и запуск нужно производить в аналогичной версии. Сама строчка «hello has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 53.0» как раз говорит нам об этом. Проверить это можно вбив фразу в тот же Гугл Переводчик.

Compiled by a more recent version of the Java Runtime

Выводы

Как видим с ошибкой» A JNI error has occurred, please check your installation and try again» при компиляции Java программы в основном сталкиваются новички. Решить проблему можно проверив версии Java при компиляции и запуске файлов программы. А так же просмотреть корректность путей к «jdkbin» и «javapath». Напишите в комментариях помогло ли вам решение и удалось ли запустить вашу первую программу.

Источник

Java virtual machine launcher jni error

Community

Participate

Eclipse IDE

Home » Newcomers » Newcomers » How to track down jni errors? (Does a «jni not found» when opening a JAR produced on a Mac with a Windows computer mean there is something missing in the Windows computer’s Java stuff, or that something was left out by Ec)

How to track down jni errors? [message #1806117] Thu, 02 May 2019 21:48
Patrick Moran
Messages: 141
Registered: March 2018
I’ve redone the setup for Java on my HP running Windows 10 very many times, and nothing has changed the error message: «A JNI error has occurred, please check your installation and try again.» I’m not sure what «your installation» refers to. Presumably it is Java JDK and/or JRE and how they are configured on the Windows unit.

Originally, my Mac was running Java 10. I suspected that was the problem, so I uninstalled it and installed the vanilla Java 8. I have made sure that in Preferences «Compiler compliance level» is set to 1.8, and Execution Environments is set for Java SE 8(1.8.0_192 labeled by Eclipse as a «perfect match.»

The JAR that I»ve made for my project works on my regular Mac and an older unit that is semi-retired and has a different OS. I had been moving the JAR from computer to computer view my website, but I just tried making a ZIP containing the JAR and support files. That attempt also failed.

I also took an old project made a year or so ago and borrowed its source files, etc. to make a new project on the new Mac. It worked, and I made a JAR for it. That JAR was successful on the HP computer.

I will add two screen shots showing how the new Mac’s Eclipse is set up. I need some way to do a better job of troubleshooting.

I would very much appreciate any help or suggestions. There are lots of people having JNI problems, but none having to do with cranky JAR files.
Thanks.

P.S.
The error message.
Java
Virtual Machine Launcher
Error: A JNI retort has occurred. please check your installation and try again.,

[Updated on: Sun, 05 May 2019 18:32]

Re: How to track down jni errors? [message #1806593 is a reply to message #1806117] Sat, 11 May 2019 08:09
Patrick Moran
Messages: 141
Registered: March 2018
I have found some clear information about JNI. See https://www.math.uni-hamburg.de/doc/java/tutorial/native1.1/concepts/index.html

It would appear that running the Java code in the application on my new Mac fed appropriate instructions to that computer, and that such activity involves calls upon the native-to-this-computer code. The JNI stuff then issues calls to systems operations on the Mac, and that works because whatever version of Java I am using knows how tp issue the right signals to the coding that is deep within the Mac operating Systemj. When the same code is transported via JAR to a computer running another system, e.g., Mac to Windows, there is at some point an instruction coming out of the Java side of things and going into the Windows operations center, but the Windows system does not know how to do whatever the code in the JAR was asking it to do. For instance, on the Mac side, the Java code would, via the JNI stuff, direct the computer to turn on the UV camera. However, on the Windows side and writing for a particular make and model of computer, there may be no way to tell the computer to turn on a camera that it does not have. In a way that is like getting a null pointer error.

So a report of a JNI error doesn’t give much specific information about what went wrong. However, it indicates that one should make sure that the version numbers of both the JRE and the JDK are the same. That’s probably not the only way for things to go wrong, however.

Re: How to track down jni errors? [message #1806606 is a reply to message #1806593] Sat, 11 May 2019 15:54
David Wegener
Messages: 1442
Registered: July 2009
Your explanation of JNI isn’t very accurate. Java programs compile into byte code that is understood by a Java Virtual Machine (JVM). A JVM is kind of like a computer simulator. When the JVM runs a Java program, it reads the the byte code instructions and «translates» them into the machine instructions of the native system that the JVM is running on. The JVM has to be built specifically for the native system. That is why there is a different JVM for Windows, Mac, and Linux.

In order to be useful, the JVM has to provide a portable way to access system resources such as files, network connections, graphics displays. The mechanisms for accessing these resources is tied directly to the native system the JVM is running on. The library/system calls needed to access a file on Windows is different from the library/system calls needed to access a file on a Mac. The JVM uses the Java Native Interface (JNI) to prove access to they system level services. Java methods that use JNI to access services are qualified with the term native (see java.lang.Class.isPrimitive for example). The native qualifier tells the JVM that the code to execute when this method is called exists in an external library. The JVM looks up the specific library call to make based on the fully qualified path name of the method and its arguments. There is a specific naming convention to enable the method to map to a specific external library reference. The JVM includes tools that allow C/C++ header files to be generated from the Java methods that are declared native. This JNI mechanism allows for Java programs to code to a portable method name and allows Java programs compiled on Windows to run on Linux or Mac computers. The Java program invokes the method and the JVM resolves the name to the appropriate external library and invokes the native code in that library.

As mentioned, Java includes native libraries for basic system interaction like read/writing files, making network connections, and drawing on the screen. These are distributed with the JVM as part of the Java Runtime Environment (JRE) whether that is a standalone JRE or included in a Java Development Kit (JDK). In addition, developers can write their own native methods. The developer has to write the native code following the rules of JNI library specification. The developer also has to provide the mechanisms that the JVM needs to locate the libraries and load them at run time. This may be the case for a peripheral such as a camera which includes a Java API library to control the camera. A JNI library would allow the Java code to execute the native code necessary to control the camera.

JNI errors produced by the JVM when a program is run indicate that there was a problem running the code associated with the native method. There can be a number of causes for this. For example, a corrupted JDK/JRE library may not be able to load in which case the JVM isn’t able to execute the code. A corrupted operating system may not be able to satisfy a system call made by the native code. For example a call may need to allocate a file on the filesystem. If the filesystem is full, the file allocation can’t succeed. For native methods provided by a third party and not directly by the JDK, a third party library or driver may need to be installed for the native code to run. Since native code requires a unique library for each system (Windows, Mac, Linux) a third party Java library will only run on platforms that have a native library written for them.

If you are seeing JNI errors when you run a jar file that works on another system, you are likely either trying to run on a corrupted Java installation or running a jar that has dependencies on a third party JNI library that is compatible/installed on the working system but not on the failing system. A corrupted Java installation will likely have problems running other Java jar files so if only this particular jar file fails, you should look for third party library dependencies.

Version number differences between a JRE and a JDK will rarely cause a JNI error. Version number differences would really only result in a JVM refusing to run code because it was compiled to be compatible with a Java version greater then the maximum version supported by the JVM. A JVM is written to run code that is compatible with a specific Java Language version and all version prior. The Java compiler marks each class file it generates with a version identifier indicating the Java Language specification that the class file complies with. As the JVM loads classes, it looks at this version. If it encounters a class file with a version beyond what it understands, it will throw an exception and likely cause the program to terminate. JNI methods are required to be backwards compatible. As new Java versions are developed, native methods won’t be changed but new methods might be added. Java code that invokes the new methods would need to be compiled with the new Java version compiler so the class file would be marked with a new Java version. If the class calling the new method attempted to run on an old JVM, the class version check would reject the class before it would be able to invoke a JNI method. Version differences between JRE and JDK would result in incompatible class version exceptions not JNI errors.

Источник

Я новичок в изучении Java. Пытаюсь запустить «hello world!» Пример того, что я запускаю ниже.

class hello {

	public static void main(String args[]) {

		System.out.println("Hello, world!");

	}

}

Javac компилирует, но созданный класс не интрепретируется. Выдается следующая ошибка:

***:~/Documents/JavaSampl$ javac hello.java
***:~/Documents/JavaSampl$ java hello
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: hello has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 53.0
	at java.lang.ClassLoader.defineClass1(java.base@9-internal/Native Method)
	at java.lang.ClassLoader.defineClass(java.base@9-internal/ClassLoader.java:939)
	at java.security.SecureClassLoader.defineClass(java.base@9-internal/SecureClassLoader.java:152)
	at jdk.internal.loader.BuiltinClassLoader.defineClass(java.base@9-internal/BuiltinClassLoader.java:553)
	at jdk.internal.loader.BuiltinClassLoader.access$200(java.base@9-internal/BuiltinClassLoader.java:88)
	at jdk.internal.loader.BuiltinClassLoader$3.run(java.base@9-internal/BuiltinClassLoader.java:466)
	at jdk.internal.loader.BuiltinClassLoader$3.run(java.base@9-internal/BuiltinClassLoader.java:460)
	at java.security.AccessController.doPrivileged(java.base@9-internal/Native Method)
	at jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(java.base@9-internal/BuiltinClassLoader.java:459)
	at jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(java.base@9-internal/BuiltinClassLoader.java:406)
	at jdk.internal.loader.BuiltinClassLoader.loadClass(java.base@9-internal/BuiltinClassLoader.java:364)
	at jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(java.base@9-internal/ClassLoaders.java:184)
	at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:419)
	at sun.launcher.LauncherHelper.loadMainClass(java.base@9-internal/LauncherHelper.java:585)
	at sun.launcher.LauncherHelper.checkAndLoadMain(java.base@9-internal/LauncherHelper.java:497)

Подскажите как это решить. Заранее спасибо!

  • Partition Wizard

  • Partition Manager

  • How to Fix A JNI Error Has Occurred in Minecraft [A Full Guide]

By Vega | Follow |
Last Updated January 05, 2023

Some Minecraft users see the “a JNI error has occurred” error when trying to start the client (game) or server (.jar). If you also encounter this issue, then you can refer to the solutions provided in this article from MiniTool Partition Wizard.

Some Minecraft users see the JNI error Minecraft server message that appears when trying to start the client or server: «A JNI error has occurred, please check your installation and try again». This issue mainly occurs in Minecraft version 21w19a and newer.

Why does this “a JNI error has occurred” error occur? Here are possible reasons:

  • The version of Java is old: Previous versions of Minecraft came with server software that was compatible with older versions of Java. However, this is not the case with the latest Minecraft update, which now requires Java to get up and running properly.
  • The corrupted system path for Java: The system variable path for Java is corrupted and tricks the Minecraft launcher into thinking that Java is not actually installed on your PC.

Whatever the cause of this problem, the solutions below will help you fix it in no time.

Solution 1: Install the Latest Java Version

This a JNI error has occurred Minecraft server error occurs when you try to start Minecraft or a Minecraft server on a PC that does not have the latest version installed. To fix this, you just need to update your current Java to the latest version.

You can complete the installation of Java’s latest version of Minecraft by following these steps:

Tip: Make sure the Minecraft launcher (Tlauncher or any other) is completely closed.

Step 1: Go to the official website to download the latest version of Java. Here you need to download the installation package you need correctly. For Windows users, they may choose to download the file ending with .exe.

download the latest version of Java

Step 2: After downloading Java, install the software on your computer. You just double-click the downloaded executable and allow the installer to make changes when asked.

Step 3: Follow the on-screen instructions to finish the installation.

After that, you can check if the “a JNI error has occurred” error still appears.

Solution 2: Remove Broken System Path Variables for Java

If the first method doesn’t work, then this “a JNI error has occurred Minecraft” error is due to a corrupted system path variable for Java.

In this case, you can fix the problem by visiting the System Properties screen and modifying the environment variables in a way that removes the Java environment variables.

To do so, here is the guide:

Step 1: Press the Win + R key to open the Run dialog box. Then type sysdm.cpl in it and press Enter.

Step 2; In the System Properties window, switch to the Advanced tab, and then click on the Environment Variables button.

Step 3: Once enter the System Variables window, under the System variables section, select Path and click on the Edit button.

Step 4: In the next window, find the environment variables for Java. Then click it and click Delete.

delete environment variables for Java

After removing the offending environment variable, restart your PC, then start Minecraft again and see if the «a JNI error has occurred » issue is fixed.

Bottom Line

Two ways for fixing Minecraft server a JNI error has occurred issue. If you have any doubts about this article or have a better way to this problem, you can share it in the comment zone.

About The Author

Vega

Position: Columnist

Vega joined MiniTool as an editor after graduation. She enjoys helping people with computer problems, including disk management, data recovery, and more. She is constantly expanding her knowledge in related fields. And she will continue to bring more easy-to-understand professional articles to help people solve various problems on the PC.

In her daily life, Vega enjoys hanging out with friends, shopping online and listening to music. She is someone who knows how to enjoy life.

  • Partition Wizard

  • Partition Manager

  • How to Fix A JNI Error Has Occurred in Minecraft [A Full Guide]

By Vega | Follow |
Last Updated January 05, 2023

Some Minecraft users see the “a JNI error has occurred” error when trying to start the client (game) or server (.jar). If you also encounter this issue, then you can refer to the solutions provided in this article from MiniTool Partition Wizard.

Some Minecraft users see the JNI error Minecraft server message that appears when trying to start the client or server: «A JNI error has occurred, please check your installation and try again». This issue mainly occurs in Minecraft version 21w19a and newer.

Why does this “a JNI error has occurred” error occur? Here are possible reasons:

  • The version of Java is old: Previous versions of Minecraft came with server software that was compatible with older versions of Java. However, this is not the case with the latest Minecraft update, which now requires Java to get up and running properly.
  • The corrupted system path for Java: The system variable path for Java is corrupted and tricks the Minecraft launcher into thinking that Java is not actually installed on your PC.

Whatever the cause of this problem, the solutions below will help you fix it in no time.

Solution 1: Install the Latest Java Version

This a JNI error has occurred Minecraft server error occurs when you try to start Minecraft or a Minecraft server on a PC that does not have the latest version installed. To fix this, you just need to update your current Java to the latest version.

You can complete the installation of Java’s latest version of Minecraft by following these steps:

Tip: Make sure the Minecraft launcher (Tlauncher or any other) is completely closed.

Step 1: Go to the official website to download the latest version of Java. Here you need to download the installation package you need correctly. For Windows users, they may choose to download the file ending with .exe.

download the latest version of Java

Step 2: After downloading Java, install the software on your computer. You just double-click the downloaded executable and allow the installer to make changes when asked.

Step 3: Follow the on-screen instructions to finish the installation.

After that, you can check if the “a JNI error has occurred” error still appears.

Solution 2: Remove Broken System Path Variables for Java

If the first method doesn’t work, then this “a JNI error has occurred Minecraft” error is due to a corrupted system path variable for Java.

In this case, you can fix the problem by visiting the System Properties screen and modifying the environment variables in a way that removes the Java environment variables.

To do so, here is the guide:

Step 1: Press the Win + R key to open the Run dialog box. Then type sysdm.cpl in it and press Enter.

Step 2; In the System Properties window, switch to the Advanced tab, and then click on the Environment Variables button.

Step 3: Once enter the System Variables window, under the System variables section, select Path and click on the Edit button.

Step 4: In the next window, find the environment variables for Java. Then click it and click Delete.

delete environment variables for Java

After removing the offending environment variable, restart your PC, then start Minecraft again and see if the «a JNI error has occurred » issue is fixed.

Bottom Line

Two ways for fixing Minecraft server a JNI error has occurred issue. If you have any doubts about this article or have a better way to this problem, you can share it in the comment zone.

About The Author

Vega

Position: Columnist

Vega joined MiniTool as an editor after graduation. She enjoys helping people with computer problems, including disk management, data recovery, and more. She is constantly expanding her knowledge in related fields. And she will continue to bring more easy-to-understand professional articles to help people solve various problems on the PC.

In her daily life, Vega enjoys hanging out with friends, shopping online and listening to music. She is someone who knows how to enjoy life.

You have encountered this JNI Error error message? Don’t panic! The problem can usually be solved quite quickly – and here you can find out how.

Have you encountered this error message or popup?

Error: A JNI error has occurred, please check your installation and try again

JNI Error Popup
Java Virtual Machine Launcher: JNI Error Popup

The problem comes from the fact that your JRE (Java Runtime Enviroment), that is your installed Java version and your JDK (Java Development Kit) do not work together correctly.

Now there are several possible solutions for you. Just choose the scenario that applies to you:

JNI Error in Windows CMD

JNI Error when starting a Minecraft Server

JNI Error in Minecraft TLauncher

JNI Error in Windows CMD

The problem can occur if you want to call a .jar file via command line (Windows CMD), e.g. via the command java -jar File.jar or if you have compiled your program with Eclipse before.

To fix the error, you need to adjust the environment variables for Java.

  • To do this, type “environment variable” in your Windows search and open the “Edit System Environment Variables” item. In this window you click on “Environment variables…”.

System properties - screenshot

System properties – screenshot
  • The “Environment variables” window opens. There you select the variable “Path” in the lower window “System variables” and click on “Edit…”.

Environment variables - screenshot

Environment variables – screenshot
  • There you look for the line where the installation path of your Java JDK is stored. In my case this is under C:Program FilesJavajdk-13.0.1bin.

If you don’t have a Java JDK installed yet, you can download and install the .exe installation file (“x64 Installer”) here.

  • If you do not have this entry, you can add it by clicking the “New” button.

Edit environment variables - screenshot

Edit environment variables – screenshot
  • Select the line with the Java JDK and click on “Move up” until the entry is at the top. Done!
  • Now you have to close and reopen the Windows-CMD once and the error should be fixed.

JNI Error when starting a Minecraft Server

If you try to start your Minecraft server via the official server.jar (error occurs since version 1.17), you may get this error message:

JNI Error Popup
Java Virtual Machine Launcher: JNI Error Popup
  • Download the latest Java JDK version as .exe file (“x64 Installer”) and install by clicking on the .jar file
  • Now the server should start again

JNI Error in Minecraft TLauncher

This error message can also appear when launching the Minecraft TLauncher.

  • Download the latest Java JDK version as .zip archive (“x64 Compressed Archive”) (see screenshot)

Java JDK Download Page

Java JDK Download Page
  • Right-click on the downloaded file and click “Extract here”.
  • Copy the unzipped folder to the directory C:Program FilesJava
  • Launch your Minecraft TLauncher and click on the gear in the bottom right corner
  • Click at “Java path” on “Browse…” and choose C:Program FilesJavajdkXbinjavaw.exe (replace the X by the name of your JDK folder).
  • Save everything – now the game should start again

Java JNI error message still appears?

  • Restart your computer
  • Uninstall old Java versions under Control Panel > Programs > Programs and Features and install the latest Java JRE and Java SDK.

I hope that you were able to fix the JNI error with the help of this post. If this is still not the case, feel free to write me a comment.

What did you think of this post?

like

dislike

Related Posts

This can also interest you


Многие новички, которые изучают программирование на Java при компиляции могут столкнуться с ошибкой «A JNI error has occurred, please check your installation and try again». Ошибка выскакивает даже если запускать совсем простой код типа «hello world!» как в примере ниже.

Пример простого кода программы

Пример простого кода Hello World!

Обычно компиляция проходит, но созданный класс не интерпретируется. У большинства пользователей ошибка появляется из-за следующих двух моментов:

  1. Неправильные пути в переменных средах;
  2. Вы компилируете файл более новой версией Java, а запустить пытаетесь на более ранней. Например компилировали при помощи Java 10, а запускаете на Java 9.

Как исправить ошибки при запуске и компиляции?

Первое, что следует проверить – пути в переменных средах. По списку первым например стоит путь:

«C:Program Files (x86)Common FilesOracleJavajavapath»

А в конце каталог до jdk:

C:Program Filesjdkbin

Операционная система компьютера находит екзешник «java.exe» и первым делом смотрит в «..javapath» и останавливает поиск. Вам нужен файл что лежит в «…jdkbin». В переменных средах сначала нужно поставить jdkbin, а потом уже javapath. В конечном результате путь должен быть примерно такой:

PATH=C:Program Filesjdkbin;C:Program Files (x86)Common FilesOracleJavajavapath;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:WindowsSystem32OpenSSH;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program Files (x86)QuickTimeQTSystem

Во втором случае всё еще проще. Если вы компилируете используя более позднюю версию Java Runtime 54, то соответственно и запуск нужно производить в аналогичной версии. Сама строчка «hello has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 53.0» как раз говорит нам об этом. Проверить это можно вбив фразу в тот же Гугл Переводчик.

Compiled by a more recent version of the Java Runtime

Compiled by a more recent version of the Java Runtime

Выводы

Как видим с ошибкой» A JNI error has occurred, please check your installation and try again» при компиляции Java программы в основном сталкиваются новички. Решить проблему можно проверив версии Java при компиляции и запуске файлов программы. А так же просмотреть корректность путей к «jdkbin» и «javapath». Напишите в комментариях помогло ли вам решение и удалось ли запустить вашу первую программу.

Актуальное на этой неделе:

Если вам на карту неожиданно пришли деньги, что делать?

11.04.2022

Если вам на карту неожиданно пришли деньги, что делать?

Когда поступают деньги на карту, владелец обычно знает, что и откуда «падает». Родственник прислал, долг…

Далее

Как добавить VPN на Андроид через настройки

06.04.2022

Как добавить VPN на Андроид через настройки

Ограничения доступа в интернет раздражает и не дает использовать интересные подключения. Проблема решается…

Далее

Как создать канал в Telegram: пошаговое руководство и советы

06.04.2022

Как создать канал в Telegram: пошаговое руководство и советы

Собственный Telegram-канал может завести любой человек. Мессенджер в данном случае никого не ограничивает. При…

Далее

Код ошибки 60-02 и 01-03 в Сбербанк Онлайн – как исправить?

19.03.2022

Код ошибки 60-02 и 01-03 в Сбербанк Онлайн – как исправить?

«Сбербанк онлайн» — это удобный сервис, позволяющий проводить финансовые манипуляции из любой точки мира….

Далее

Consider:

public class LoginCumReg implements ActionListener, KeyListener {

    private JFrame form;
    private JTextField txtunm;
    private JTextField txtnm;
    private JTextField txteml;
    private JButton cmdcreate;
    private JPasswordField txtpass;
    private JPasswordField txtpassreg;
    private JButton cmdok;
    private JLabel lblunm;
    private JLabel lblpass;
    private JLabel lbleml;
    private JLabel lblpassreg;
    private JLabel lblnm;
    private JPanel panel_1;

    public LoginCumReg() {
        // Construct components
        form = new JFrame("Sign Up");
        form.getContentPane().setFont(
                new Font("Plantagenet Cherokee", Font.BOLD, 18));
        txtunm = new JTextField(5);
        txtunm.addKeyListener(this);
        txtunm.setBounds(637, 55, 100, 25);
        txtnm = new JTextField(5);
        txtnm.setBounds(637, 228, 100, 25);
        txteml = new JTextField(5);
        txteml.setBounds(637, 264, 100, 25);
        cmdcreate = new JButton("Create Account");
        cmdcreate.setBounds(527, 350, 188, 25);
        txtpass = new JPasswordField(5);
        txtpass.setBounds(637, 91, 100, 25);
        txtpassreg = new JPasswordField(5);
        txtpassreg.setBounds(637, 300, 100, 25);
        cmdok = new JButton("OK");
        cmdok.setBounds(527, 139, 100, 25);
        lblunm = new JLabel("UserName");
        lblunm.setBounds(527, 55, 73, 25);
        lblpass = new JLabel("Password");
        lblpass.setBounds(527, 91, 100, 25);
        lbleml = new JLabel("Email ID");
        lbleml.setBounds(527, 264, 100, 25);
        lblpassreg = new JLabel("Password");
        lblpassreg.setBounds(527, 300, 100, 25);
        lblnm = new JLabel("Full Name");
        lblnm.setBounds(527, 228, 100, 25);

        // form.setResizable(false);

        // Adjust size and set layout
        form.setPreferredSize(new Dimension(800, 450));

        form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        form.getContentPane().setLayout(null);

        // Add components
        form.getContentPane().add(txtunm);
        form.getContentPane().add(txtnm);
        form.getContentPane().add(txteml);
        form.getContentPane().add(cmdcreate);
        form.getContentPane().add(txtpass);
        form.getContentPane().add(txtpassreg);
        form.getContentPane().add(cmdok);
        form.getContentPane().add(lblunm);
        form.getContentPane().add(lblpass);
        form.getContentPane().add(lbleml);
        form.getContentPane().add(lblpassreg);
        form.getContentPane().add(lblnm);

        cmdcreate.setActionCommand("Create Account");
        cmdcreate.addActionListener(this);
        cmdok.setActionCommand("Login");

        JPanel panel = new JPanel();
        panel.setBounds(502, 29, 254, 154);
        panel.setFont(new Font("Palatino Linotype", Font.PLAIN, 14));
        panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,
                null, null), "LOGIN", TitledBorder.LEADING, TitledBorder.TOP,
                null, null));
        panel.setBackground(SystemColor.controlHighlight);
        form.getContentPane().add(panel);

        panel_1 = new JPanel();
        panel_1.setBounds(500, 204, 254, 186);
        panel_1.setFont(new Font("Palatino Linotype", Font.PLAIN, 14));
        panel_1.setBorder(new TitledBorder(new EtchedBorder(
                EtchedBorder.RAISED, null, null), "SIGN UP",
                TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panel_1.setBackground(SystemColor.controlHighlight);
        form.getContentPane().add(panel_1);

        JLabel lblNewLabel = new JLabel("New label");
        lblNewLabel.setBounds(91, 139, 286, 101);
        lblNewLabel.setIcon(new ImageIcon(
                "C:\Users\JAsh\Desktop\Projects\JAsh.png"));
        form.getContentPane().add(lblNewLabel);

        JPanel panel_2 = new JPanel();
        panel_2.setBounds(77, 118, 315, 145);
        panel_2.setBorder(new EtchedBorder(EtchedBorder.RAISED,
                SystemColor.activeCaptionBorder, SystemColor.menu));
        panel_2.setBackground(SystemColor.controlHighlight);
        form.getContentPane().add(panel_2);
        cmdok.addActionListener(this);

        form.setResizable(false);
        form.pack();
        form.setVisible(true);
        System.out.println("const..");
    }

    public static void main(String[] args) {
        new LoginCumReg();
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        // TODO Auto-generated method stub

        if (ae.getActionCommand().equals("Create Account")) {
            new Registration(txtnm.getText(), txteml.getText(), new String(
                    txtpassreg.getPassword()));
            form.setVisible(false);
        }

        if (ae.getActionCommand().equals("Login")) {
            try {
                if (txtunm.getText().equalsIgnoreCase("admin")
                        && new String(txtpass.getPassword()).equals("admin")) {
                    form.setVisible(false);
                    new Admin();
                } else {
                    DataBase db = new DataBase();
                    db.connect();
                    String sql = "SELECT * FROM LOGIN WHERE USERNAME='"
                            + txtunm.getText() + "'";
                    ResultSet rs = db.getDDL(sql);
                    boolean found = false;
                    while (rs.next()) {
                        if (rs.getString("Password").equals(
                                new String(txtpass.getPassword()))) {
                            found = true;
                            form.setVisible(false);
                            String name = rs.getString("FullName");
                            Session.startSession(txtunm.getText(), name);
                            new FacultyWelcome();
                        }
                    }
                    if (!found)
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Invalid Credentials");
                    db.close();
                }
            }
            catch (Exception e) {
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

        // TODO Auto-generated method stub
        // JOptionPane.showMessageDialog(new JFrame(), arg0.getKeyChar() + "-" + arg0.getKeyCode());
    }
}

The above code works perfectly on my friend’s laptop and throws this error on my laptop. I have running the code on Eclipse v4.2 (Juno) using Java 7.

I have also tested and run a lot of Java programs on my laptop all works well. This is the only program which gives such an error.

How can I fix this problem?

Hi, This is a common problem when you want to run a java program using the command line. The problem is occurring for so many reasons. Most of the cause is the different versions of the Java JDK and the Java JRE versions.

I have been having this problem for a while, but now I have figured it out.

It turns out that Java JDK 15 have both the JRE and the JDK inside the bin folder of the Java 15 JDK. (I have always believed that JRE and JDK are different application, but it turns out things have changed)

My problem was that I had Java JDK 15 installed on my computer

At the same time, I had Java 8 (JRE) installed on my computer.

So my computer is getting confused.

The error looks like:

Error: A JNI error has occurred, please check your installation and try again
 Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of
 the Java Runtime (class file version 59.0), this version of the Java Runtime only recognizes class file versions up to
  52.0
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(Unknown Source)
         at java.security.SecureClassLoader.defineClass(Unknown Source)
         at java.net.URLClassLoader.defineClass(Unknown Source)
         at java.net.URLClassLoader.access$100(Unknown Source)
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

Solution:

Open the command prompt to check the version of the java and java compiler:

Typed the following commands:

java -version  

// this gave me Java 8

After that, type

javac -version

// this gave me Java 15

a JNI error has occurred please check your installation and try again Exception in thread main

In other words, my program is getting compiled with Java 15 and I am trying to run with Java 8. This is the problem of ” a JNI error has occurred please check your installation and try again Exception in thread main ……”

To solve the problem, I uninstalled Java 8 JRE from my computer.

Went back to the command prompt to check if “java -version” and “javac -version” are returning the same version number or not, In my case it’s yes, it is returning Java 15.

a JNI error has occurred please check your installation and try again Exception in thread main

Tried recompiling my program, and running it. It Worked!!

a JNI error has occurred please check your installation and try again Exception in thread main

Wow! It works fine. If not then comment……

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка kernelbase dll код события 1000