- Установка JDK на компьютере под управлением Windows 10
- Шаг 1: Загрузка установщика с официального сайта
- Шаг 2: Инсталляция JDK
- Шаг 3: Настройка операционной системы
- Шаг 4: Проверка работы JDK
- JDK Installation for Microsoft Windows
- System Requirements
- Installation Instructions Notation
- Installation Instructions
- Downloading the Installer
- Running the JDK Installer
- Java Start Menu
- Installing the JDK Silently
- Updating the PATH Environment Variable (Optional)
- Starting to Use the JDK
- Uninstalling the JDK
- Uninstalling the JDK in Silent Mode
- Finding the JDK Registry Key and UninstallString Value
- Installed Directory Tree
- Installation Troubleshooting
- Corrupt Cabinet File
- System Error During Decompression
- Program Cannot Be Run in DOS Mode
- Private Versus Public JRE
- Source Files in Notepad
Установка JDK на компьютере под управлением Windows 10
Начинающие разработчики, изучающие язык программирования Java, сталкиваются с надобностью установки на свой компьютер фирменного компонента под названием JDK (Java Development Kit), ведь в нем присутствует необходимый компилятор и стандартные библиотеки, позволяющие реализовывать привычные функции на этом ЯП. Большинство даже самых неопытных программистов знают, как инсталлировать подобные файлы на свой компьютер, однако некоторые сталкиваются с трудностями при попытке установки и настройки компонента. Поэтому сегодня мы хотим затронуть эту тему, детально расписав процесс добавления JDK в Windows 10.
Шаг 1: Загрузка установщика с официального сайта
Весь процесс начинается с загрузки всего одного файла формата EXE с официального сайта. Если вы уже сделали это или прекрасно знаете, как производится подобная задача, просто переходите к следующему шагу. В противном случае ознакомьтесь с этой инструкцией.
- Воспользуйтесь ссылкой выше, чтобы попасть на официальный сайт Oracle. Там вас интересует строка «JDK Download». Нажмите по ней левой кнопкой мыши, чтобы начать загрузку компонента.
Следующим этапом будет выбор версии для своей операционной системы. В нашем случае будет выбран «Windows x64 Installer». Обратите внимание, что на 32-битных системах Java Development Kit не поддерживается.
После нажатия по соответствующей кнопке откроется всплывающее окно, где следует подтвердить лицензионное соглашение, а уже потом кликнуть по активной кнопке, чтобы начать скачивание исполняемого файла.
Шаг 2: Инсталляция JDK
Этот этап выполняется еще проще предыдущего, поскольку от пользователя требуется только следовать инструкциям, отобразившимся в открытом окне. Однако давайте на нем тоже остановимся более детально, чтобы больше ни у кого не возникло вопросов по этой теме.
- После открытия исполняемого файла начнется подготовка к инсталляции. Это не займет много времени, а вам нужно лишь не закрывать активное окно.
При открытии приветственного меню переходите к следующему шагу, щелкнув по кнопке «Next».
Начнется процедура установки, занимающая несколько минут. Продолжительность зависит от скорости жесткого диска и общего быстродействия операционной системы.
Вы получите уведомление о том, что инсталляция прошла успешно. В этом же окне находится кнопка «Next Steps». При нажатии на нее откроется страница в браузере, где будет находиться вся сопутствующая документация и уроки по взаимодействию с установленным компонентом.
Шаг 3: Настройка операционной системы
Этот этап считается самым важным и сложным, поскольку именно от него зависит корректность функционирования установленного компонента в дальнейшем. Суть заключается во внесении новых переменных окружения, что позволит работать компилятору и встроенным в JDK библиотекам. Производится конфигурация следующим образом:
- Откройте «Пуск» и перейдите в меню «Параметры», кликнув по специально отведенной кнопке на левой панели.
Здесь вам нужен раздел «Система».
Опуститесь вниз и выберите категорию «О системе».
Внизу окна находится надпись «Сведения о системе», по которой и следует нажать для перехода в необходимое меню.
Откроется категория Панели управления «Система». Здесь на левой панели щелкните по кликабельной надписи «Дополнительные параметры системы».
Отобразится окно «Свойства системы», где на первой же вкладке «Дополнительно» воспользуйтесь кнопкой «Переменные среды».
Добавьте новую переменную для системы, кликнув по кнопке «Создать».
Задайте ей название. По умолчанию используется «JAVA_HOME», поэтому и мы рекомендуем придерживаться этого правила. В поле «Значение переменной» вставьте путь к папке JDK. Стандартно он имеет вид C:\Program Files\java\jdk-13.0.2 , где 13.0.2 — номер установленной версии компонента.
Сохраните изменения и убедитесь в том, что новая строка появилась в блоке «Системные переменные».
После этого там же отыщите переменную «Path» и щелкните по ней дважды, чтобы открыть окно редактирования.
Пропишите там %JAVA_HOME%\bin , указав тем самым только что созданную переменную, и сохраните изменения.
По завершении данной операции рекомендуется перезагрузить компьютер, чтобы все изменения вступили в силу. Уже после этого можно смело переходить к тестированию функционирования JDK или сразу к работе с языком программирования, если проверка работоспособности не требуется.
Шаг 4: Проверка работы JDK
Завершающий этап сегодняшнего материала заключается в проверке работоспособности Java Development Kit, что иногда требуется сделать для подтверждения корректной обработки запросов компилятором и успешной интеграции библиотек. Осуществляется эта задача через стандартную консоль путем ввода всего двух команд.
- Откройте приложение «Командная строка» любым удобным методом, например, отыскав ее через «Пуск».
Введите там echo %JAVA_HOME% и нажмите на клавишу Enter для активации команды.
Следующей строкой отобразится место сохранения всех файлов компонента и будет означать то, что переменная функционирует корректно.
Далее напишите javac -version и снова активируйте эту команду.
В результате вы получите строку с информацией о текущей рабочей версии JDK.
Установка JDK не займет много времени и в большинстве случаев производится без каких-либо дополнительных трудностей. Сразу после этого можно приступать к написанию кода на Java и быть уверенным в том, что он корректно скомпилируется, а библиотеки будут подключены.
JDK Installation for Microsoft Windows
See JDK 7 and JRE 7 Installation Guide for general information about installing JDK 7 and JRE 7.
The following topics are covered:
System Requirements
See Oracle JRE 7 and JDK 7 Certified System Configurations for information about supported platforms, operating systems, and browsers.
See Windows System Requirements for JDK and JRE for minimum processor, disk space, and memory requirements.
Note:
- The JDK and JRE have a version string that enables you to determine the version number. See Java Platform Standard Edition 7, Names and Versions Version Number for information about Java SE 7 version numbers.
- The JDK has the option of installing the public JRE. For more information about JRE installation, see JRE Installation for Microsoft Windows.
- If you have any difficulties, see the Troubleshooting section at the end of this document or submit a bug report for your installation problem.
Installation Instructions Notation
For any text in this document that contains the following notation, you must substitute the appropriate update version number:
For example, if you were downloading the JDK installer for 32-bit systems for update 1.7.0_01, the file name: jdk-7 -windows-i586.exe would become jdk-7u1-windows-i586.exe .
Similarly, if you were downloading the JDK installer for 64-bit systems for update 1.7.0_01, the file name jdk-7 -windows-x64.exe would become jdk-7u1-windows-x64.exe .
Installation Instructions
In this procedure, you will run the self-installing executable file to unpack and install the JDK. As part of the JDK, this installation includes an option to include the public Java Runtime Environment. (The JDK also contains a private JRE for use only by its tools; see Private Versus Public JRE for more information.)
Install the JDK by doing the following:
Downloading the Installer
If you save the self-installing executable file to disk without running it from the download page at the web site, note that its byte size provided on the download page. After the download has completed, verify that you have downloaded the full, uncorrupted software file.
Running the JDK Installer
You must have administrative permissions in order to install the JDK on Microsoft Windows.
The file jdk-7 -windows-i586-i.exe is the JDK installer for 32-bit systems. The file jdk-7 -windows-x64.exe is the JDK installer for 64-bit systems. If you downloaded either file instead of running it directly from the web site, double-click the installer’s icon. Then, follow the instructions the installer provides. The installer may ask you to reboot your computer. When finished with the installation, you can delete the downloaded file to recover disk space.
Note: Installers for JDK 7u6 and later install the JavaFX SDK and integrate it into the JDK installation directory. Installers for JDK 7u2 to 7u5 install the JDK first, then start the JavaFX SDK installer, which installs JavaFX SDK in the default directory C:\Program Files\Oracle\JavaFX 2.0 SDK or C:\Program Files (x86)\Oracle\JavaFX 2.0 SDK on 64-bit operating systems. If you want to install the JavaFX SDK (version 2.0.2) with JDK 7u1 or earlier, see Installing JavaFX for more information.
Java Start Menu
Starting with JDK 7u40 release, Java menu items are added to the Windows Start Menu to provide easy access to Java resources.
During JDK install, a Java Development Kit folder is created in the Windows Start Menu, which contains the following items:
- Reference Documentation: opens the Online API documentation web page.
- Java Mission Control: opens the Java Mission Control profiling and diagnostics tools suite.
During JDK install and uninstall processes, the appropriate start menu items are updated to be associated with the latest JDK version on the system.
Note: Java Mission Control is a commercial feature available to users with a Java SE Advanced license.
Installing the JDK Silently
You can perform a silent, non-interactive, JDK installation by using the command-line arguments. The following table lists example installation scenarios and the commands required to perform them:
Installation Scenario | Command |
---|---|
Install the public JRE in silent mode | |
Install development tools and source code in silent mode but not the public JRE | |
Install development tools, source code, and the public JRE in silent mode | |
Install the public JRE in the specified directory C:\test\ in silent mode |
Updating the PATH Environment Variable (Optional)
You can run the JDK without setting the PATH environment variable, or you can optionally set it so that you can conveniently run the JDK executable files ( javac.exe , java.exe , javadoc.exe , and so forth) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable file every time you run it, such as:
It is useful to set the PATH variable permanently so it will persist after rebooting.
To set the PATH variable permanently, add the full path of the jdk1.7.0\bin directory to the PATH variable. Typically, this full path looks something like C:\Program Files\Java\jdk1.7.0\bin . Set the PATH variable as follows on Microsoft Windows:
Click Start, then Control Panel, then System.
Click Advanced, then Environment Variables.
Add the location of the bin folder of the JDK installation for the PATH variable in System Variables. The following is a typical value for the PATH variable:
Note:
- The PATH environment variable is a series of directories separated by semicolons ( ; ) and is not case-sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.
- You should only have one bin directory for a JDK in the path at a time. Those following the first instance are ignored.
- If you are not sure where to add the path, add it to the right of the value of the PATH variable.
- The new path takes effect in each new command window you open after setting the PATH variable.
Starting to Use the JDK
If you are new to developing and running programs in the Java programming language, see The Java Tutorial online for some guidance. Note especially the tutorial trails under the heading Trails Covering the Basics.
You can also download the JDK documentation from the Java SE Downloads page.
Uninstalling the JDK
If you should ever want to uninstall the JDK, use the «Add/Remove Programs» utility in the Microsoft Windows Control Panel.
Uninstalling the JDK in Silent Mode
You can use the command line for uninstalling the JDK.
For example, to uninstall Java 7 update 271, run the command:
This command can be run from anywhere.
The msiexec.exe executable is located in the windows system directory.
A reboot is required only if some files are in use during uninstallation; it is not necessary everytime. However, to manually suppress reboot while uninstalling, append REBOOT=R option to the command.
setup.log» option to the command if you want to create a log file describing the uninstallation status.
Windows Installer dialog appears prompting you for confirmation. Click Yes to uninstall JDK.
Finding the JDK Registry Key and UninstallString Value
Go to Start and type regedit.
In the Registry Editor, go to HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/CurrentVersion/Uninstall .
Under the Uninstall folder, you will find many registry entries within curly brackets.
Click Edit and then Find.
Highlight Uninstall folder before performing search for a particular registry.
Enter version string as value to find corresponding registry key. For JDK registry key, enter 1.7.0.271.
The registry key is highlighted on the right-hand side of the pane and values of various uninstall strings are displayed on the left-hand pane.
Note the value of the UninstallString.
Installed Directory Tree
See JDK and JRE File Structure for a description of the directory structure of the JDK. (Note that the file structure of the JRE is identical to that of the JDK’s jre directory.)
Installation Troubleshooting
Below are some tips for working around problems that are sometimes seen during or following an installation. For more troubleshooting information, see Troubleshooting Java SE:
Corrupt Cabinet File
If you see the error message «corrupt cabinet file,» then the file you have downloaded is corrupted. Check the file size against the expected file size listed in these instructions. If sizes do not match, try downloading the bundle again. (A cabinet file contains compressed application, data, resource, and DLL files.)
System Error During Decompression
If you see the error message «system error during decompression,» then you might not have enough space on the disk that contains your TEMP directory.
Program Cannot Be Run in DOS Mode
If you see the error message «This program cannot be run in DOS mode,» then do the following:
- Open the MS-DOS shell or Command Prompt window.
- Right-click the title bar.
- Select Properties.
- Choose the Program tab.
- Click the Advanced button.
- Ensure that the item «Prevent MS-DOS-based programs from detecting Windows» is not selected.
- Select OK.
- Select OK again.
- Exit the MS-DOS shell.
- Restart your computer.
Private Versus Public JRE
Installing the JDK also installs a private JRE and optionally a public copy. The private JRE is required to run the tools included with the JDK. It has no registry settings and is contained entirely in a jre directory (typically at C:\Program Files\jdk1.7.0\jre ) whose location is known only to the JDK. On the other hand, the public JRE can be used by other Java applications, is contained outside the JDK (typically at C:\Program Files\Java\jre1.7.0 ), is registered with the Windows registry (at HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft ), can be removed using Add/Remove Programs, might be registered with browsers, and might have the java.exe file copied to the Windows system directory (which would make it the default system Java platform).
Source Files in Notepad
In Microsoft Windows, when you create a new file in Microsoft Notepad and then save it for the first time, Notepad usually adds the .txt extension to the file name. Therefore, a file you name Test.java is saved as Test.java.txt . It is important to note that you cannot see the .txt extension unless you turn on the viewing of file extensions (in Microsoft Windows Explorer, unselect «Hide file extensions for known file types» under Folder Options). To prevent the .txt extension, enclose the file name in quotation marks, such as «Test.java» , when typing it into the Save As dialog box.
On the other hand, Microsoft WordPad does not add the .txt extension if you specify another extension. However, you must save the file as «Text Document».