Java paths get windows

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.)
Читайте также:  Не грузится рабочий стол linux

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.

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 метода и придумать предназначение для этой программы. Например, можно написать программу, которая будет логировать все свои действия: выводить в консоль название файла или папки до/после входа в них. На этом все — до встречи! 🙂

Читайте также:  Системное программное обеспечение операционные системы windows linux mac

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 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:

Читайте также:  Тайловый оконный менеджер для windows

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.

Java paths get windows

The Path is obtained by invoking the getPath method of the default FileSystem .

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

This method iterates over the installed providers to locate the provider that is identified by the URI scheme of the given URI. URI schemes are compared without regard to case. If the provider is found then its getPath method is invoked to convert the URI.

In the case of the default provider, identified by the URI scheme «file», the given URI has a non-empty path component, and undefined query and fragment components. Whether the authority component may be present is platform specific. The returned Path is associated with the default file system.

The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that

  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

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