Javac не является внутренней или внешней командой windows 10

Причина ошибки "javac не является внутренней или внешней командой" - заданы некорректные переменные среды. Войдите в "Дополнительные параметры системы" - "Переменные среды". Создайте CLASSPATH и PATH.
  • Причина ошибки

  • Исправление

Работая с Java кодом через консоль, может появится ошибка: “javac не является внутренней или внешней командой”. Как ее исправить читайте в этой статье.

Причина ошибки

Причина ошибки – заданы некорректные “переменные среды”. Соответственно, необходимо указать правильные.

Исправление

На рабочем столе откройте “Этот компьютер”:

  1. Нажмите слева вверху “Свойства”, затем слева в меню – “Дополнительные параметры системы”.Система Windows
  2. В открывшейся вкладке “Дополнительно” в самом низу выберите “Переменные среды”.Переменные среды
  3. Откроется содержимое. Нажмите в каждом окне поочередно “Создать”.Переменные среды
  4. В окне “Новая пользовательская переменная” пропишите CLASSPATH.Новая пользовательская переменная
  5. Затем в окне “Новая системная переменная” укажите переменную PATH. В поле “Значение” пропишите директорию к пакету JDK.Новая системная переменная
  6. Перезагрузите Windows.

Кроме того, чтобы выполнить Javac, вы можете в командной строке прописать полный путь к консоли. К примеру:

"C:Program FilesJavajdk1.8.0_102binjavac.exe" MyFile.java

Рекомендую также не забывать про обновления Java. Чтобы их не пропустить, используйте программу Java Update Available.

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:Program FilesJavajdkxxxxbin
  2. Start-menu search for «environment variable» to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:>set
ALLUSERSPROFILE=C:ProgramData
APPDATA=C:UserscraigAppDataRoaming
CommonProgramFiles=C:Program FilesCommon Files
CommonProgramFiles(x86)=C:Program Files (x86)Common Files
CommonProgramW6432=C:Program FilesCommon Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:>echo %PATH%
C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPower
Shellv1.0;C:ProgramDataMicrosoftWindowsStart MenuPrograms;C:UserscraigAppData
RoamingMicrosoftWindowsStart MenuPrograms;C:msys64usrbin;C:msys64mingw64bin;C:
msys64mingw32bin;C:Program Filesnodejs;C:Program Files (x86)Yarnbin;C:Users
craigAppDataLocalYarnbin;C:Program FilesJavajdk-10.0.2bin;C:ProgramFilesGitcmd;
C:Program FilesOracleVirtualBox;C:Program Files7-Zip;C:Program FilesPuTTY;C:
Program Fileslaunch4j;C:Program Files (x86)NSISBin;C:Program Files (x86)Common Files
AdobeAGL;C:Program FilesIntelIntel(R) Management Engine ComponentsDAL;C:Program
FilesIntelIntel(R) Management Engine ComponentsIPT;C:Program FilesInteliCLS Client;
C:Program Files (x86)IntelIntel(R) Management Engine ComponentsDAL;C:Program Files
(x86)IntelIntel(R) Management Engine ComponentsIPT;C:Program Files (x86)InteliCLS
Client;C:UserscraigAppDataLocalMicrosoftWindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package’s name includes the words «Development Kit» in it.

Don’t use set

(If you weren’t planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:>:: DON'T DO THIS
C:>set PATH=C:Program FilesJavajdk1.7.0_09bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:Program FilesJavajdk1.7.0_09bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:>:: DON'T DO THIS EITHER
C:>set PATH=C:Program FilesJava<enter the correct Java folder here>bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle’s installer places versions of Java under C:Program FilesJava (or C:Program Files (x86)Java). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:Program FilesJavajdkxxxxbin

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won’t get in your way; C:Java is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for «environment variable»
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control PanelSystem and SecuritySystem » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you’re at it, you may as well uninstall old Java versions, too. And remember that you don’t need to have both a JDK and a JRE.

If you have C:ProgramDataOracleJavajavapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn’t matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn’t much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you’re at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:Program FilesJavajdkxxxx.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd’s environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

  • What are PATH and other environment variables, and how can I set or use them?
  • How do I set or change the PATH system variable?
  • How to set the path and environment variables in Windows
  • How to set Path environment variables in Windows 10

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:Program FilesJavajdkxxxxbin
  2. Start-menu search for «environment variable» to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:>set
ALLUSERSPROFILE=C:ProgramData
APPDATA=C:UserscraigAppDataRoaming
CommonProgramFiles=C:Program FilesCommon Files
CommonProgramFiles(x86)=C:Program Files (x86)Common Files
CommonProgramW6432=C:Program FilesCommon Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:>echo %PATH%
C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPower
Shellv1.0;C:ProgramDataMicrosoftWindowsStart MenuPrograms;C:UserscraigAppData
RoamingMicrosoftWindowsStart MenuPrograms;C:msys64usrbin;C:msys64mingw64bin;C:
msys64mingw32bin;C:Program Filesnodejs;C:Program Files (x86)Yarnbin;C:Users
craigAppDataLocalYarnbin;C:Program FilesJavajdk-10.0.2bin;C:ProgramFilesGitcmd;
C:Program FilesOracleVirtualBox;C:Program Files7-Zip;C:Program FilesPuTTY;C:
Program Fileslaunch4j;C:Program Files (x86)NSISBin;C:Program Files (x86)Common Files
AdobeAGL;C:Program FilesIntelIntel(R) Management Engine ComponentsDAL;C:Program
FilesIntelIntel(R) Management Engine ComponentsIPT;C:Program FilesInteliCLS Client;
C:Program Files (x86)IntelIntel(R) Management Engine ComponentsDAL;C:Program Files
(x86)IntelIntel(R) Management Engine ComponentsIPT;C:Program Files (x86)InteliCLS
Client;C:UserscraigAppDataLocalMicrosoftWindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package’s name includes the words «Development Kit» in it.

Don’t use set

(If you weren’t planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:>:: DON'T DO THIS
C:>set PATH=C:Program FilesJavajdk1.7.0_09bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:Program FilesJavajdk1.7.0_09bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:>:: DON'T DO THIS EITHER
C:>set PATH=C:Program FilesJava<enter the correct Java folder here>bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle’s installer places versions of Java under C:Program FilesJava (or C:Program Files (x86)Java). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:Program FilesJavajdkxxxxbin

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won’t get in your way; C:Java is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for «environment variable»
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control PanelSystem and SecuritySystem » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you’re at it, you may as well uninstall old Java versions, too. And remember that you don’t need to have both a JDK and a JRE.

If you have C:ProgramDataOracleJavajavapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn’t matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn’t much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you’re at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:Program FilesJavajdkxxxx.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd’s environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

  • What are PATH and other environment variables, and how can I set or use them?
  • How do I set or change the PATH system variable?
  • How to set the path and environment variables in Windows
  • How to set Path environment variables in Windows 10

При компиляции кода через командную строку, с помощью команды javac, выдается вот такая ошибка

введите сюда описание изображения

Путь к bin прописан. Вроде все правильно, но все равно выдает ошибку. В чем может быть дело?

insolor's user avatar

insolor

44.1k15 золотых знаков52 серебряных знака92 бронзовых знака

задан 3 авг 2017 в 17:24

solaeternus's user avatar

1

Причина ошибки — заданы некорректные «переменные среды». Соответственно, необходимо указать правильные.

На рабочем столе откройте «Этот компьютер»:

  1. Нажмите слева вверху «Свойства», затем слева в меню —
    «Дополнительные параметры системы».
  2. В открывшейся вкладке «Дополнительно» в самом низу выберите
    «Переменные среды».
  3. Откроется содержимое. Нажмите в каждом окне поочередно «Создать».
  4. В окне «Новая пользовательская переменная» пропишите CLASSPATH.
  5. Затем в окне «Новая системная переменная» укажите переменную PATH. В
    поле «Значение» пропишите директорию к пакету JDK.
  6. Перезагрузите Windows.

Кроме того, чтобы выполнить Javac, вы можете в командной строке прописать полный путь к консоли. К примеру: C:Program FilesJavajdk1.8.0_102binjavac.exe" MyFile.java

Источник

ответ дан 3 авг 2017 в 17:28

Daniil Dubchenko's user avatar

1

Если не помогло, добавление в CLASSPATH, то добавь тот же самый путь в PATH, если там уже что-то есть то добавляй через точку с запятой ‘;’

ответ дан 24 ноя 2017 в 16:50

Ivan's user avatar

IvanIvan

111 бронзовый знак

1

Если после добавления путей ничего не поменялось, то сделай копии папок jdk в Programm Files/java и Programm Files(x86)/java

ответ дан 4 фев 2019 в 16:34

Defered's user avatar

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

C:Program FilesJavajdk1.8.0_201bin

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

ответ дан 13 апр 2019 в 6:17

Daniil Briz's user avatar

Надо перенести JAVA_HOME в самое начало переменной PATH, чтобы она была раньше стандартного пути, который прописался при установке:

C:Program Files (x86)Common FilesOracleJavajavapath

0xdb's user avatar

0xdb

51.2k194 золотых знака56 серебряных знаков227 бронзовых знаков

ответ дан 26 авг 2018 в 10:03

Andrew's user avatar

AndrewAndrew

1198 бронзовых знаков

В данной статье мы рассмотрим, как исправить ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.»

Данная ошибка может возникнуть при попытке запуска команды java в командной строке Windows. Первая причина ошибки – отсутствие установленной Java в системе. Вторая причина ошибки – Java установлена, но некорректно настроена. Давайте разберёмся, как это исправить.

Есть два пакета Java – JRE для запуска программ, написанных на Java и JDK – набор инструментов для разработки ПО на Java. Если вам требуется только запускаться программы, вам потребуется лишь JRE, если вы планируете разрабатывать программы – вам потребуется JDK.

Шаг 1. Установка Java

Сначала нужно определить, есть ли у вас в системе установленная Java. Проверьте следующие каталоги в системе:

%PROGRAMFILES%Java
%PROGRAMFILES(X86)%Java

Если какой-то из этих каталогов открывается и вы видите Java, значит, она установлена и её требуется настроить.

Пример установленной Java (JRE 8)

Если вы не находите подобных каталогов, вам потребуется установить Java. Как скачать, установить и настроить Java, вы можете узнать на этой странице – Установка JDK в Windows

Шаг 2. Настройте Java

Итак, вы установили Java. Теперь её нужно немного настроить, чтобы можно было запускать её из командной строки.

Выполните в командной строке команду:

control /name microsoft.system

Откроется окно «Система». Нажмите на «Дополнительные параметры системы» и в открывшемся окне нажмите кнопку «Переменные среды…»

В окне «Переменные среды» нажмите кнопку «Создать…»

Укажите следующие значения полей:

Имя переменной: JAVA_HOME
Значение переменной: <путь к установленной Java>bin

Нажмите «OK».

В окне «Переменные среды» выберите переменную «Path» и нажмите кнопку «Изменить»:

В открывшемся окне нажмите кнопку «Создать» и введите значение %JAVA_HOME%bin

Нажмите «OK».

Шаг 3. Проверка установки

Откройте командную строку (Win+R, введите cmd):

В командной строке введите следующую команду для проверки установленной Java:

java -version

Если вы видите корректный вывод программы наподобие этого, значит, вы корректно установили и настроили Java.

Если же вы снова видите ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.», значит, вы некорректно установили или настроили Java. Вернитесь на несколько шагов ранее и проверьте, что вы всё делаете правильно.

Заключение

В данной статье вы научились решать ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.» Вы научились скачивать, устанавливать и настраивать Java.

WindowsTen » Инструкции » Исправляем ошибку: «javac не является внутренней или внешней командой»

Работая с Java кодом через консоль, может появится ошибка: «javac не является внутренней или внешней командой». Как ее исправить читайте в этой статье.

Причина ошибки

Причина ошибки — заданы некорректные «переменные среды». Соответственно, необходимо указать правильные.

"Javac" не является внутренней или внешней командой, исполняемой программой или пакетным файлом

Исправление

На рабочем столе откройте «Этот компьютер»:

  1. Нажмите слева вверху «Свойства», затем слева в меню — «Дополнительные параметры системы».Система Windows
  2. В открывшейся вкладке «Дополнительно» в самом низу выберите «Переменные среды».Переменные среды
  3. Откроется содержимое. Нажмите в каждом окне поочередно «Создать».Переменные среды
  4. В окне «Новая пользовательская переменная» пропишите CLASSPATH.Новая пользовательская переменная
  5. Затем в окне «Новая системная переменная» укажите переменную PATH. В поле «Значение» пропишите директорию к пакету JDK.Новая системная переменная
  6. Перезагрузите Windows.

Кроме того, чтобы выполнить Javac, вы можете в командной строке прописать полный путь к консоли. К примеру:

"C:Program FilesJavajdk1.8.0_102binjavac.exe" MyFile.java

Рекомендую также не забывать про обновления Java. Чтобы их не пропустить, используйте программу Java Update Available.

Хороший сайт? Может подписаться?

Рассылка новостей из мира IT, полезных компьютерных трюков, интересных и познавательных статей. Всем подписчикам бесплатная компьютерная помощь.

проблема в том, что я обновился до Windows 10, и теперь я устанавливаю свои инструменты для программирования, и теперь, когда я установил JDK 7 Java, когда я пытаюсь использовать в cmd команду:
— «javac»

результат этого: «javac» не распознается как внутренняя или внешняя команда…

но я отредактировал путь с правильной ссылкой jdk, потому что когда я использую «java», это нормально.

теперь я попробовал в консоли с этой командой: PATH=%PATH%;"C:Program FilesJavajdk1.7.0_79bin"

и когда я извлекаю эту команду, когда я использую «javac», она работает, но теперь, когда я открываю другую консоль, она не работает или когда я перезапускаю консоль, эта команда не распознается.

в чем может быть проблема?

19 ответов


java является частью JRE, а не JDK.

вам нужно добавить JDK bin в системный путь, в

«Панель Управления» / System / Advanced / «Переменные Среды»


вот как я настраиваю системную переменную в Windows 10:

enter image description here

10

автор: Mahesh Sonavane


после добавления C:Program файлыJavajdk1.8.0_73bin для системных переменных я отключил командную строку и открыл другую. Потом сработало.


может быть, немного поздно, но у меня была такая же проблема.

Нажмите кнопку «Переместить вверх» для пути Java и переместите его сверху.

Исправлена проблема для меня


Я совершенно новичок в java и потратил часы, пытаясь решить проблемы с PATH и CLASSPATH. Был один человек, который сказал перезапустить командную строку после изменения переменных среды; это было для меня. При тестировании различных конфигураций перед тестированием обязательно перезапустите командную строку. Похоже, есть как минимум 2 разных способа настройки. Я пошел со следующим:

1) в системных переменных, добавить

JAVA_HOME = c:program файлы (x86)javajdk1.8.0_121

2) в системных переменных, добавьте к существующему пути…

%JAVA_HOME%bin


просто добавьте C:Program файлыJavajdk1.7.0_80bin как путь в переменных среды. нет необходимости добавлять java.exe и javac.exe в этом направлении. ЭТО РАБОТАЕТ

3

автор: Sreenivas Gundlapalli


Я добавил ниже путь в переменной среды

;%переменной JAVA_HOME%/bin вместо %переменной JAVA_HOME%ОГРН

в моем случае , это решить проблему


у меня была такая же проблема в Windows 10 —java -version команда работала, но javac -version не было. Я сделал три вещи:—9—>

(1) я загрузил последнюю версию jdk (не JRE) и установил его. Затем я добавил jdk/bin путь tan o переменная окружения. В моем случае это было C:Program FilesJavajdk-10bin. Мне не нужно было добавлять ; для Windows 10.

(2) переместите этот путь в начало всех остальных путей.

(3) Удалите все другие пути Java, которые могут существовать.


по какой-то причине мне удалось добавить кавычки в папку path в windows 10. не C:Program файлы1.8.0_111\на Java с JDK bin, но «C:Program файлы1.8.0_111\Ява версии JDK бин».

1

автор: Mściwój Ogórkowski


наконец-то! убедитесь, что нет пробелов до и после пути и поместите двоеточие с обеих сторон без пробелов

1

автор: Yazan Al-Hinnawi


путь для текущего пользователя, вместо этого вы можете добавить CLASSPATH и ниже ссылку поможет вам больше путь и путь к классам


Я добавил ниже путь в переменной среды

C:Program файлыпапку Javajdk1.8._91 ОГРН

а затем скомпилировал программу, но получил ошибку, затем я перезапустил систему и снова скомпилировал программу

в этот раз это сработало :)


добавьте путь java к переменным среды и переместите его в начало всех доступных там путей. У меня получилось.


чтобы быть уверенным о своем пути, вы можете использовать двойные кавычки " чтобы найти путь или если вы находитесь в Windows, вы можете перейти к пути, чтобы выбрать .


в окне поиска введите «переменные среды» это должно дать вам ссылку на редактирование переменных. На странице редактирования переменных есть верхний раздел и Нижний раздел в нижнем разделе Добавить новый, введите путь C:Program FilesJavajdk-10bin это отлично сработало для меня, и он все время находит компилятор.


вид избиения мертвой лошади сейчас, но я хочу прояснить одну вещь, которая может быть не совсем очевидной. Да, действительно, вам нужно отредактировать переменную среды PATH, как уже неоднократно указывалось. Ключом для меня было редактировать путь под система переменные. Я нечаянно отредактировал путь под пользователей переменные. Почему это так важно? На моей машине я должен войти в систему как администратор для редактирования переменных среды. Поэтому редактирование пользовательских переменных не помогло потому что я запускаю командную строку под своей учетной записью login (non-admin). Гррр!

кроме того, я обнаружил, что закрытие окна командной строки и его повторное открытие после обновления переменной PATH было необходимо. Изменение порядка значений, добавление точки с запятой и т. д. для меня это не имело значения.

Ура


что я сделал:-
я набрал ; случайно впереди в переменной path, а затем нажмите OK, после этого, если я снова отредактирую его, он нигде не будет на той же странице, что и раньше, он открыл новую страницу, как определено для пользовательских переменных, а затем я смог удалить двойные кавычки перед переменной PATH.
тогда все работает нормально. :)

Я только что сделал это

ура


добавить

PATH = C:Program FilesJavajdk1.8.0_66bin 

наdvanced system setting. Затем Выберите Environment Variable.


для windows 10 пользователи используют путь Java (расположение JDK Bin) как «C:Program FilesJavajdk-9.0.1bin» он будет работать.

-1

автор: Ramachandrudu R


Сегодня я скачал и установил JDK, настроил среду Java, следуйте на онлайн-стороне

Метод открыл окно DOS попробовалиjava -versionс участиемjavaЕсть результаты, но

входитьjavacВсегда всегда появляются: не внутренние или внешние проблемы. Затем найдите метод онлайн,

Различные вкусыПопробуйте, после более чем на один час усилия, наконец, решены.

Решение:

Есть проблема в конфигурации пути, проблема.

Обычно мы все за пути;%JAVA_HOME%bin;%JAVA_HOME%jrebin;

Это нормально, но на Windows10 может произойти ошибка.

Нам нужно разделить их на 2 строки в покое, не добавляйте битовый номер

%JAVA_HOME%bin

%JAVA_HOME%jrebin

Этот метод успешен, но у меня все еще есть ошибка.

В это время мы должны поставить%JAVA_HOME%  Перейдите на наш Абсолютный путь JDK

Например:

E:Javajdkbin 

E:JAVAjdkjrebin   (E:JAVAjd K — мой абсолютный путь JDK)


Наконец, вы можете увидеть Javac в окне DOS.


Хотя проблема решена, я до сих пор не знаю, какой «принцип» основан.

Поэтому в будущем вам нужно сохранить свой собственный курс и спросить себя.

Если кто-то знает, вы можете оставить сообщение, я буду рад узнать.

Понравилась статья? Поделить с друзьями:
  • Java скачать for windows 10 x64
  • Java последняя версия x64 windows 10 для майнкрафт
  • Java ошибка 1603 как исправить windows 10 64 bit
  • Java не является приложением win32 windows xp
  • Java не является внутренней или внешней командой windows 10