- Window add Java to Path
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged java windows path or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to set the java path and classpath in windows-64bit
- 5 Answers 5
- How to add Java bin folder path in Windows path system
- 2 Answers 2
- Files, Path
- Paths
- Files
- Java File Path Windows/Linux [closed]
- 5 Answers 5
Window add Java to Path
I used to use My Computer -> Environment variables to set up PATH for Java, but where can I find the same in Windows 8?
2 Answers 2
Type: Control Panel
In the control panel search box, enter:
Edit environment variables for your account
Edit the system environment variables
The environment variable dialog itself is very similar to the one under previous versions of Windows.
Set Environment variable using Command Prompt in easy two steps:
Example of windows SET command:
Step 1. Print the PATH environment variable
Step 2. Add one variable to path ( For example : Java SDK )
Verify the Change
Not the answer you’re looking for? Browse other questions tagged java windows path or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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.
How to add Java bin folder path in Windows path system
i have a problem with running a Java software which is made for Windows. Actually I want run it on kali Linux but whenever I try to run the soft it tells me add Java bin folder path in Windows path system variable.
and thats my Java version
How can I solve this?
2 Answers 2
Add Variables — Java
First, you need to Locating the Environment Variables
1. Open up the system properties (WinKey + Pause) and you should see the below screen.
2. From the system properties, tab select the «Advanced» link. This should take you to the below screen.
3. From the System Properties screen select the «Advanced Tab». On this screen click the «Environment Variables» button.
4. You should now be seeing something like the below screen.
Now You Are Ready To Add Variables — JAVA
In the system variables section click in the «New» button.
In here enter the variable name : JAVA_HOME
Enter the variable value as the location of the java jdk installed in the previous section. (This is assuming you already have installed Java SDK. If you haven’t now is the time to do it)
For Example of my location below. (Please note the variable value will vary depending on your install location and version of the jdk)
Click ok to complete this action. Once completed you should see the JAVA_HOME variable in the list of system variables.
Next, you need to add the newly created JAVA_HOME variable on to your path.
To do this locate the «Path» variable in the system variables list. Select it and click the edit button.
This should bring up the below option.
Scroll to the end of the «variable value» field and append on the following
;%JAVA_HOME%\bin
Click «OK» to confirm and leave the edit path screen.
Once complete click «OK» to confirm and leave the Environment variables screen.
Next, open a new command prompt (Winkey + R then type cmd) and run «java -version» to verify that it is correctly installed.
If it is you should see something similar to the below screenshot.
Files, Path
Paths
getFileName() — возвращает имя файла из пути;
getParent() — возвращает «родительскую» директорию по отношению к текущему пути (то есть ту директорию, которая находится выше по дереву каталогов);
getRoot() — возвращает «корневую» директорию; то есть ту, которая находится на вершине дерева каталогов;
startsWith() , endsWith() — проверяют, начинается/заканчивается ли путь с переданного пути:
Вывод в консоль:
testFile.txt
C:\Users\Username\Desktop
C:\
true
false
Обрати внимание на то, как работает метод endsWith() . Он проверяет, заканчивается ли текущий путь на переданный путь. Именно на путь, а не на набор символов.
Сравни результаты этих двух вызовов:
Вывод в консоль:
false
true
В метод endsWith() нужно передавать именно полноценный путь, а не просто набор символов: в противном случае результатом всегда будет false, даже если текущий путь действительно заканчивается такой последовательностью символов (как в случае с “estFile.txt” в примере выше).
Кроме того, в Path есть группа методов, которая упрощает работу с абсолютными (полными) и относительными путями.
boolean isAbsolute() — возвращает true, если текущий путь является абсолютным:
Вывод в консоль:
Path normalize() — «нормализует» текущий путь, удаляя из него ненужные элементы. Ты, возможно, знаешь, что в популярных операционных системах при обозначении путей часто используются символы “.” (“текущая директория”) и “..” (родительская директория). Например: “./Pictures/dog.jpg” обозначает, что в той директории, в которой мы сейчас находимся, есть папка Pictures, а в ней — файл “dog.jpg”
Так вот. Если в твоей программе появился путь, использующий “.” или “..”, метод normalize() позволит удалить их и получить путь, в котором они не будут содержаться:
Вывод в консоль:
C:\Users\Java\examples
C:\Users\examples
Path relativize() — вычисляет относительный путь между текущим и переданным путем.
Вывод в консоль:
Username\Desktop\testFile.txt
Полный список методов Path довольно велик. Найти их все ты сможешь в документации Oracle. Мы же перейдем к рассмотрению Files .
Files
С помощью метода filter() отбираем только те строки из файла, которые начинаются с «Как».
Проходимся по всем отобранным строкам с помощью метода map() и приводим каждую из них к UPPER CASE.
Объединяем все получившиеся строки в List с помощью метода collect() .
preVisitDirectory() — логика, которую надо выполнять перед входом в папку;
visitFileFailed() — что делать, если вход в файл невозможен (нет доступа, или другие причины);
postVisitDirectory() — логика, которую надо выполнять после захода в папку.
У нас такой логики нет, поэтому нам достаточно SimpleFileVisitor . Логика внутри метода visitFile() довольно проста: прочитать все строки из файла, проверить, есть ли в них нужное нам содержимое, и если есть — вывести абсолютный путь в консоль. Единственная строка, которая может вызвать у тебя затруднение — вот эта: На деле все просто. Здесь мы просто описываем что должна делать программа после того, как выполнен вход в файл, и все необходимые операции совершены. В нашем случае необходимо продолжать обход дерева, поэтому мы выбираем вариант CONTINUE . Но у нас, например, могла быть и другая задача: найти не все файлы, которые содержат «This is the file we need», а только один такой файл. После этого работу программы нужно завершить. В этом случае наш код выглядел бы точно так же, но вместо break; было бы: Что ж, давай запустим наш код и посмотрим, работает ли он. Вывод в консоль: Нужный файл обнаружен! C:\Users\Username\Desktop\testFolder\FileWeNeed1.txt Нужный файл обнаружен! C:\Users\Username\Desktop\testFolder\level1-a\level2-a-a\FileWeNeed2.txt Нужный файл обнаружен! C:\Users\Username\Desktop\testFolder\level1-b\level2-b-b\FileWeNeed3.txt Отлично, у нас все получилось! 🙂 Если тебе хочется узнать больше о walkFileTree() , рекомендую тебе вот эту статью. Также ты можешь выполнить небольшое задание — заменить SimpleFileVisitor на обычный FileVisitor , реализовать все 4 метода и придумать предназначение для этой программы. Например, можно написать программу, которая будет логировать все свои действия: выводить в консоль название файла или папки до/после входа в них. На этом все — до встречи! 🙂
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: