Java windows user path

Установка Java (JDK) в Windows и Linux, переменная PATH и JAVA_HOME

Java — язык общего назначения, основанных на классах, поддерживающий многопоточность и являющийся объектно-ориентированным. Программы на Java компилируются в так называемый byte-код, который в свою очередь запускается Виртуальной Машиной Java (Java Virtual Machine — JVM), независимо от архитектуры компьютера. На данный момент последняя версия Java двенадцатая.

Ниже мы рассмотрим — как установить Java на Windows и Linux. Для каждой из платформ создана своя версия JDK, JRE и JVM, хотя сами программы на Java и не меняются от платформы к платформе (что логично).

Давайте проясним несколько вещей перед тем, как мы начнем.

  • JDK (Java Development Kit) — эта штука нужна для разработчиков на Java (то есть нас) и включает в себя инструменты разработки, документирования, упаковки и так далее (в том числе компилятор Javac, Javadoc, Jar-упаковщик и дебаггер).
  • JRE (Java Runtime Environment) — сюда включены библиотеки Java, которые необходимы для запуска Java-программ. Эта штука нужна обычным пользователям и не содержит инструментов для разработки.
  • JVM (Java Virtual Machine) — это и есть сама виртуальная машина Java, которая непосредственно и запускает наши Java-программы (байткод). Ее реализация написана для множества железа и платформ.

Установка Java (JDK) в Windows

Первым делом необходимо скачать JDK с официальной страницы Oracle. В нашем случае нужна версия под Windows, в самом низу.

После установки запустите скачанный exe-файл и установите его на ваш компьютер. Как только вы это сделаете, нужно будет настроить окружение.

Перейдите в Панель управления -> Система и безопасность -> Система. На вкладке «Дополнительно» нажмите на «Переменные среды», как показано ниже:

Теперь нужно найти и дополнить переменную PATH так, чтобы она содержала путь до установленной Java. Выберите PATH и нажмите «Изменить»:

Вы увидите список уже установленных переменных. Сейчас необходимо нажать «Новый» и добавить путь, по которому установлена Java (каталог bin!). По умолчанию это обычно «C:\Program Files(x86)\Java\jdk\bin».

Нажмите «Готово» (или «Ок»), сохраните настройки и на этом всё готово! Чтобы проверить, что установка прошла корректно, откройте консоль и введите:

Если вы получили сведения о версии Java, значит всё хорошо.

Установка Java (JDK) на Linux

В Linux есть несколько способов установить Java. Мы опишем самый простой и быстрый, с использование терминала. И в данном случае мы установим OpenJDK. OpenJDK — это бесплатная и свободная реализация виртуальной машины Java, причем очень популярная.

Читайте также:  Проверить микрофон наушников windows 10

Откройте терминал и напишите команду для установки пакета:

Осталось подтвердить установку и на этом всё, Java установлена! Единственное, что меняется — это прописывание путей до компилятора.

Чтобы прописать JAVA_HOME в окружение, выполните следующую команду (только убедитесь, что такой каталог уже есть):

Чтобы прописать компилятор Java в PATH, выполните другую команду (опять же, ваши пути до Java могут отличаться от моих):

На этом установка закончена. Чтобы проверить, что всё работает правильно, достаточно написать в терминале:

О том, как же всё-таки писать на Java, мы расскажем в следующий раз.

How to get the Desktop path in java

I think this will work only on an English language Windows installation:

How can I make this work for non English Windows?

8 Answers 8

I use a french version of Windows and with it the instruction:

works fine for me.

I think this is the same question. but I’m not sure!:

Reading it I would expect that solution to return the user.home, but apparently not, and the link in the answer comments back that up. Haven’t tried it myself.

I guess by using JFileChooser the solution will require a non-headless JVM, but you are probably running one of them.

This is for Windows only. Launch REG.EXE and capture its output :

Seems not that easy.

But you could try to find an anwser browsing the code of some open-source projects, e.g. on Koders. I guess all the solutions boil down to checking the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Desktop path in the Windows registry. And probably are Windows-specific.

If you need a more general solution I would try to find an open-source application you know is working properly on different platforms and puts some icons on the user’s Desktop.

there are 2 things.

  1. you are using the wrong slash. for windows it’s \ not / .
  2. i’m using RandomAccesFile and File to manage fles and folders, and it requires double slash ( \\ ) to separate the folders name.

How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?

Java is a very popular programming language which provides a different component in order to run, develop Java applications. JRE or Java Runtime Environment is used to run Java application. JDK or Java Development Kit is used to develop Java applications. In this tutorial, we will learn how to set up Java, JRE, and JDK operating system path variables in order to work properly.

Locate JRE or JDK Path

Before starting the configuration we have to locate the JRE or JDK path. JRE or JDK generally installed on the Program Files or Program Files(x86) directory under the Java directory like below.

Locate JRE or JDK Path

and under the Java directory the JDK is residing.

Locate JRE or JDK Path

Set Java HOME_PATH Environment Variable

Now we have learned the path of the Java, JRE or JDK installation. We can set this path as Java HOME_PATH environment variable. We will open the computer properties with by running sysdm.cpl in the Run menu like below. We can also open it from the File Explorer -> Computer -> Right Click.

Читайте также:  Как активировать ableton live 10 mac os

Open System Properties

In the system properties, we will navigate to the Advanced tab which provides the Environment Variables button like below.

Open Environment Variables

Below we can see the environment variables menu where we will create the JAVA_HOME system variable and set the path accordingly. We click to the New in order to create a new system variable.

Create New System Variable

Here we will set the Variable Name as JAVA_HOME and the Variable Value the path or Java, JRE or JDK which is C:\Program Files\Java\jdk-12 in this example. Then we will click OK.

Set JAVA Executable Path

If we want to run java.exe or similar executables provided by JRE or JDK we have to add the path of Java in the Path variable like below. We select the system variable named Path and click to the Edit .

Here we click to New which will add a new line to the existing values.

Here we will set the bin folder path which is C:\Program Files\Java\jdk-12\bin in this example.

Add Path System Variable

Then we will click OK and OK in the environment variables screen which will save and activated new path configuration.

Check Java Is Working

We can check the new path configuration simply opening a new command line interface MS-DOS. Then just type java -version which will execute java.exe with the -version option. We can see the current java binary version by running it.

3 thoughts on “How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?”

What is the point in setting the JAVA_HOME to the path to the jdk install folder path if you then edit the Path variable and add the full path to the jdk bin folder? Shouldn’t you make use of the JAVA_HOME variable and add %JAVA_HOME%\bin to the Path instead.

@James Coffey, maybe the point of setting JAVA_HOME is just in preparation for GlassFish:
https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html
Still, the author could make use of it in Path as you say, but maybe the author is just trying to keep it simple.

THANK YOU SO MUCH. YOU SAVED MY LIFE. I need to use java in jupyter

Правка путей для Javac или настройка JDK на Windows

После успешной установки JDK перейдите в командную строку. Для этого у Вас есть два варианта:

  1. Нажмите сочетание клавиш Win+R -> введите «cmd» -> нажмите клавишу Enter -> откроется окно командной строки;
  2. Откройте меню пуск -> введите команду «cmd» -&gt в поле «Поиск»; дождитесь, пока Windows найдёт эту программу -> в получившемся списке поиска найдите программу с названием «cmd.exe» или «cmd» (зависит от настроек WIndows) -> кликните на эту программу -> откроется окно командной строки;
Читайте также:  Windows and walls перевод

Теперь наберите команду «javac». Если вылезло много информации — это хорошо и в дальнейшей инструкции Вы не нуждаетесь.
Если же у Вас вылезла ошибка » «javac» не является внутренней или внешней командой, исполняемой программой или пакетным файлом.» — то читайте ниже.

Откройте «Мой компьютер» -> кликните правой клавишей мыши -> нажмите на вкладку «Свойства» -> слева найдите «Дополнительные параметры системы» -> кликните на эту надпись -> откроется новое окно.

Откроется данное окно:

Кликните на кнопку «Переменные среды…» и откроется такое окно:

В нижнем окне кликните один раз по строке, начинающейся словом «Path», и нажмите на кнопку «изменить». Откроется ещё одно окошечко:

Кликните по кнопке «Создать». В том месте, где курсор будет мигать, введите путь до папки «bin», находящейся в папке Java. Если Вы не изменяли путь установки при инсталляции JDK, то путь будет таким: «C:\Program Files\Java\jdk1.8.0_144\bin». Данную строку и нужно прописать в месте мигания курсора

Нажмите кнопку «ОК». На этом вся настройка путей Windows закончена. Лучше перезагрузите компьютер (но, может, этого и не понадобится, зависит от настроения WIndows).

Проверка

Теперь нужно убедиться, что всё работает верно. Откройте командную строку и наберите команду javac. Должен появиться длинный список.

Если всё так, то поздравляю!

Если не так, то проверьте, всё ли правильно сделано.

Таким нехитрым образом мы разобрались с темой: «Правка путей для Javac или настройка JDK на Windows»!

Java File Path Windows/Linux [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed last year .

what is the best solution to create file path in Java for this two OS. Application will be used for this os , the i need to create universal String.

for example : For Linux:

Or is the best solution to generate 2 .jar files for this OS.

Thank a lot guys.

5 Answers 5

The best thing is to let java decide that for you like this

You can use slash character as file separator for both OS, in other words you can use C:/PDFMalwareDataAnalyser/Txt/ instead of C:\\PDFMalwareDataAnalyser\\Txt\\ it will still work on Windows OS.

Use System.getProperty(«os.name») for obtaining os name, depends on it set path to resource:

Try this line of code and according to the string return you can adjust your code

Personally I think you’d better get the folder passed in by a system property:

java -Dfolder=C:\PDFMalwareDataAnalyser\Txt\ myapp

This one you can use like this:

Or pass the folder by a program argument:

java myapp C:\PDFMalwareDataAnalyser\Txt\

And then use it like this:

But if you’re sticking to use constants in your code, you can use it like this:

Or a newer version of this would be:

Or you could also read a property file and store the path in that one. This would work for different OSes, you only have to create the property files before:

Оцените статью