- How to set the java path and classpath in windows-64bit
- 5 Answers 5
- Getting My Documents path in Java
- 8 Answers 8
- Original answer:
- How to get the real path of Java application at runtime?
- 13 Answers 13
- How to get the Desktop path in java
- 8 Answers 8
- Установка Java (JDK) в Windows и Linux, переменная PATH и JAVA_HOME
- Установка Java (JDK) в Windows
- Установка Java (JDK) на Linux
How to set the java path and classpath in windows-64bit
I have installed java on windows-64bit OS. but when I execute javac, it is failing with the
error message no such command is available». I have created following environmental variable
CLASSPATH C:\Program Files (x86)\Java\jdk1.6.0_05\lib
5 Answers 5
Add the appropriate javac path to your PATH variable. java.exe will be found under the bin directory of your JDK. E.g.
Before answering your question, just wann ans this simple question : Why we need PATH and CLASSPATH?
Answer:
1) PATH: You need to set PATH to compile Java source code, create JAVA CLASS FILES and Operating System to load classes at runtime.
2) CLASSPATH: This is used by JVM and not by OS.
Answer to your question :
Just make sure you have Modified PATH variable (Windows System Environmental Variable) so that it points to bin dir which contains all exe for example: java,javac and etc. In my case it is like this : ;C:\Program Files\Java\jre7\bin.
So, it doesn’t matter your system is 32 bit/64 bit until and unless you specify/Modify the PATH variable correctly.
Actually, the most conventional way of getting it done on Windows is
- Go to Control Panel
- Click System
- Open Advanced settings
- Click Environment Variables.
Path is one of the variables under «System Variables». This is where the system will search when you try to execute a command.
- just append the full path to the Bin folder under your Java installation path. You can copy it using Windows Explorer to avoid typing it manually
- click OK to close the dialogs.
To verify, open the command window aka console window (for example, WindowsKey-R cmd.exe ) and run:
If the java bin folder is in the path, the system will find and execute the javac.exe file located there, and you will see your Java version. Something like:
Very Simple:
You need to set the two environment variables only; PATH and java
=>Right Click on My computer
=>Properties
=>Click on left hand side bar menu «Advanced system settings» => Click on «Environment Variables» button refer below fig.
=>Follow the below steps to Set User variable and System variable.
To Set User variable named as «PATH«
- Click on «New» button in user variables section.
- Set the variable name as «PATH» and variable value as per your java installed version.(Shown in below fig.)
To Set System variable named as «java«
Click on «New» button in System variable tab.
Set the variable name as «java» and variable value as per your java installed version.(Shown in below fig.) Refer below images for the reference.
Getting My Documents path in Java
I need to find my documents path using Java. The following code doesn’t give me «accurate» loation
What should be the other way around?
P.S: I don’t want to use the JFileChooser Dirty trick.
8 Answers 8
You can get it using a registry query, no need for JNA or admin rights for that.
Obviously this will fail on anything other than Windows, and I am not certain whether this works for Windows XP.
EDIT: Put this in a working sequence of code:
Note this will lock the process until «reg query» is done, which might cause trouble dependeing on what you are doing.
That’s easy, JFileChooser finds it for you
I hope this helps someone
Since the most upvoted answer from @xchiltonx uses JFileChooser I would like to add that, regarding performance, this is faster than using JFileChooser :
In my PC, JFileChooser aproach needed 300ms, and calling FileSystemView directly needed less than 100ms.
Note: The question is a possible duplicate of How to find “My Documents” folder in Java
Note in 2020: The ShellFolder class seems to be missing on Linux (tested with openjdk8), so IvanRF’s answer is likely better.
Original answer:
The best way I’ve found is to use AWTs:
I have redirected my Documents folder to the D: drive, and it successfully fetches this directory. It also does so in about 40 ms (on my machine). Using FileSystemView takes about 48 ms, and new JFileChooser() about 250 ms.
All three of these methods actually use ShellFolder under the hood, and the difference with FileSystemView is negligible, but calling it directly avoids the overhead of the other two.
Note: You can also cast this directly to File instead of implicitly getting the toString() method of it, which can help you further:
How to get the real path of Java application at runtime?
I am creating a Java application where I am using log4j. I have given the absolute path of configuration log4j file and also an absolute path of generated log file(where this log file are generated). I can get the absolute path of a Java web application at run time via:
but in the context of a normal Java application, what can we use?
13 Answers 13
It isn’t clear what you’re asking for. I don’t know what ‘with respect to the web application we are using’ means if getServletContext().getRealPath() isn’t the answer, but:
- The current user’s current working directory is given by System.getProperty(«user.dir»)
- The current user’s home directory is given by System.getProperty(«user.home»)
- The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation() .
And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation() ?
If you’re talking about a web application, you should use the getRealPath from a ServletContext object.
Hope this helps.
Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:
Simply call getProgramDirectory() and you should be good either way.
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.
- you are using the wrong slash. for windows it’s \ not / .
- i’m using RandomAccesFile and File to manage fles and folders, and it requires double slash ( \\ ) to separate the folders name.
Установка 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, причем очень популярная.
Откройте терминал и напишите команду для установки пакета:
Осталось подтвердить установку и на этом всё, Java установлена! Единственное, что меняется — это прописывание путей до компилятора.
Чтобы прописать JAVA_HOME в окружение, выполните следующую команду (только убедитесь, что такой каталог уже есть):
Чтобы прописать компилятор Java в PATH, выполните другую команду (опять же, ваши пути до Java могут отличаться от моих):
На этом установка закончена. Чтобы проверить, что всё работает правильно, достаточно написать в терминале:
О том, как же всё-таки писать на Java, мы расскажем в следующий раз.