Папка java в linux

How to set JAVA_HOME for Java?

You can set your JAVA_HOME in /etc/profile as Petronilla Escarabajo suggests. But the preferred location for JAVA_HOME or any system variable is /etc/environment .

Open /etc/environment in any text editor like nano or gedit and add the following line:

JAVA_HOME="/usr/lib/jvm/open-jdk" 

(java path could be different)

Use source to load the variables, by running this command:

Then check the variable, by running this command:

Usually most linux systems source /etc/environment by default. If your system doesn’t do that add the following line to ~/.bashrc (Thanks @pje)

When i tried to run Android Studio (that has IntelliJ IDEA as a base), i had an error message very similar to @advocate’s: «‘tools.jar’ seems to be not in Android Studio classpath.» After fiddling a lot with JAVA_HOME without success, i decided to take a look at studio.sh, the shellscript that starts Android Studio. As a wild guess, i set JDK_HOME to the same value expected for JAVA_HOME, and voila! It installed without great problems.

For those doing software development, don’t put your JAVA_HOME in /etc/environment unless you want to reboot everytime you switch JDK versions.

This is a temporary solution, as others pointed out. No one would want to run source every time they restart their bash.

As others have pointed out, this doesn’t stick between terminal sessions. What I did to address this is just added the line source /etc/environment to the top of my bash config file ~/.bashrc so that it loads all my environment settings on startup. Working for me so far.

Источник

How to find path to java?

That tells the command java resides in /usr/bin/java.

$ ls -l /usr/bin/java lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java 

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java .

Dig deeper using the same method above:

$ ls -l /etc/alternatives/java lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java 

So, thats the actual location of java: /usr/local/jre.

Читайте также:  Чем читать html файлы

You could still dig deeper to find other symbolic links.

export JAVA_HOME=$(dirname $(dirname $(update-alternatives --list javac))) 

To make this seemingly over done setting clearer, on my Ubuntu linux machine with open JDK 8 installed:

$ update-alternatives --list java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java $ update-alternatives --list javac /usr/lib/jvm/java-8-openjdk-amd64/bin/javac 

but what we need is the path to the directory containing bin of the JDK. So ask for the location of javac and then use dirname twice.

See man update-alternatives for more.

Be aware of the possibility that people might have two JDK’s installed. To always use the first one as your JAVA_HOME you can use head : JAVA_HOME=$(dirname $(dirname $(update-alternatives —list javac 2>&1 | head -n 1)))

Starting from January 2019, the licensing model for Oracle Java has changed. PPAs such as ‘ppa:webupd8team/java’ used in many Java installation tutorials now become unavailable.

Here I would like to share how I installed Java 8 on Ubuntu 16.04, and set the Java path in terminal.

Installation

I followed the instruction on the official documentation to install Java with .tar.gz

Path setting

The instruction is also from the official documentations. The steps to set up Java path are much simpler here.

After performing all the steps, restart the terminal and run ‘java -version’ to verify installation.

Источник

В какой папке находится default-jdk?

Доброго времени суток, начал изучать java, занимаюсь на oc linux дистрибутив mint, читаю книгу Хорстмана, там говорится перейди в папку с jdk/bin и распакуйте стандартную библиотеку из архива src.zip, устанавливал по умолчанию, «sudo apt-get install defaul-jdk» в какой папке это дело всё находится? просто не могу найти, искал через поиск папок,но не в одной из тех нету bin и тем более src.zip, очень на вас рассчитываю, заранее спасибо.

TheSpbra1n

Не слушайте тех, кто в debian/ubuntu/mint вам _не_ _советует_ ставить из пакета, больше проблем получите, да и систему засрёте.

Если поставили из пакета, то сделайте «update-alternatives —config java» , в выводе команды будет нужный вам путь .

Читайте также:  Html form type mail

TheSpbra1n: Надо заранее привыкать делать все правильно. А java из репов подходит только для запуска плагинчиков в браузере или чего-то еще. Но никак ни для разработки, обучения или тем более продуктива.

PS Несмотря на наши разногласия, приношу Вам извинения за оскорбления, которые у меня вырвались. Извините, был взволнован, предлагаю остаться при своих мнениях, каждый в конце-концов имеет право на свое мнение, и это не повод для оскорблений. Свои посты я отредактирую.

TheSpbra1n

Обосную, почему в debian-base дистрибутивах лучше использовать пакеты:

1. Тот же оракл уже предлагает дистрибутив в виде пакета
2. Ставя пакет — вы знаете, что зависимости удовлетворены, а распаковывая архив — получаете просто набор файлов
3. Ставя другой дистрибутив, который по зависимостям потребует JAVA , вы всё равно поставите пакет, после чего системная java по умолчанию будет направлена на неё
4. Если вы скачали java из архива — руками прописывайте путь до неё в ПО которая будет с ним работать
5. Если несколько разработчиков будут ставить java из архива в разное время, то есть вероятность, что у них будут разные версии ( а если разработчков больше сотни ? )
6. Ставя из пакетов сразу несколько версий ( 6,7,8,9 ) — я переключаюсь на нужную из них одной командой, вам надо будет опять же руками прописывать нужные пути
7. Поддержка серверов в которых «умники» наставили всё из архивов — ужасна
8. Для проверки наличия security апдейтов мне нужно выполнить — apt-get update , вам — мониторить архивы на сайте.
9. Ставя дистрибутивы на сервера из одно и того-же репозитория я гарантирую, что на всех серверах у меня будет стоять одна и та же версия. Вы же вносите хаос, и не дай бог во время деплоя вы заявите, что в репах версия «х.у.10» , а вы разрабатывали ПО под «х.y.16» , потому что такой был архив на сайте
10. На устранение багов и помощь коллегам, при установке из архива, уходит больше времени, первый поставил — но не знает где указать путь до java или как её сделать дефолтной, у другого дефолтная java другая, третий скачал архив в один каталог и случайно захардкодил путь до _своего_ каталога из архива , в итоге: у пятерых так же и работает, а на эксплуатационных серверах не работает.
11. С помощью того же ansible управление серверами можно легко автоматизировать, параллельно устанавливать и обновлять java сразу на куче серверов, а с архивом что? лишний гемморой.

Читайте также:  Php генерация неповторяющихся чисел

Источник

How to find my current JAVA_HOME in ubuntu?

To display JAVA_HOME variable path, type in terminal:

If nothing appears then set it with this:

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64 

This will differ according to your JDK type and version.

For displaying it again, follow the first command.

Follow JREs from different vendors on the same system, for using different JDK’s or switch between JDK’s.

It gives «/usr/lib/jvm/java-6-sun». But I have installed java 7. When I check it using «java -version» it gives java version «1.7.0_45» Java(TM) SE Runtime Environment (build 1.7.0_45-b18) Java HotSpot(TM) Server VM (build 24.45-b08, mixed mode)

then execute second command for setting JAVA_HOME variable. NOTE: JAVA_HOME doesn’t make jdk default, it just makes JAVA_HOME variable set to a path & if you want to use different jdk installed on same machine then check my answer, I have edited it.

@Jax-L But now when I give echo JAVA_HOME it just displays as «JAVA_HOME». The path I gave is not displaying.

export works only until you restart. Or you add export to the .bashrc login script. But the correct way to set such environment variables is in /etc/environment

If you have JDK 1.6 (corresponding to Java 6) or a newer version installed, you should have a program named jrunscript in your PATH . You can use this to find the corresponding JAVA_HOME . Example:

$ jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));' /opt/local/jdk1.7.0_76/jre 

You could set the environment variable like this:

$ export JAVA_HOME="$(jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));')" 

Note that the JRE doesn’t include jrunscript , so this will only work if you install the JDK, not just the JRE.

Источник

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