- 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
- Pathосные новшества JDK7. Работа с файловой системой
- Класс Path
- Файлы и атрибуты файлов. Управление метаданными.
- Обход дерева файлов
- Path Operations
- Creating a Path
- Retrieving Information about a Path
- Removing Redundancies From a Path
- Converting a Path
- Joining Two Paths
- Creating a Path Between Two Paths
- Comparing Two Paths
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.
Pathосные новшества JDK7. Работа с файловой системой
Класс Path
Прежде чем перейти к более интересному материалу, необходимо рассмотреть базовый класс Path.
Класс Path включает в себя различные методы, которые могут быть использованы для получения информации о пути, получения доступа к элементам пути, преобразования пути в другие формы, извлечения части пути. Существуют также методы для сравнения строк пути и методы для удаления избыточности.
Для создания экземпляра класса Path, воспульзуемся статическим методом get класса Paths, позволяющего создать путь из строки или URI.
Path path1 = Paths. get ( «/home/iam/folder» ) ;
Path path2 = Paths. get ( «C: \\ this \\ my \\ folder» ) ;
Path path3 = Paths. get ( «file:///Users/user/myfile.txt» ) ;
После того как экземпляр Path создан, мы можем получить некоторую информацию о пути:
//Path path = Paths.get(«C:\\home\\joe\\foo»); // Microsoft Windows syntax
Path path = Paths. get ( «/home/iam/folder» ) ; // Solaris syntax
System . out . format ( «toString: %s%n» , path. toString ( ) ) ; //—>/home/iam/folder
System . out . format ( «getName: %s%n» , path. getName ( ) ) ; //—>folder
System . out . format ( «getName(0): %s%n» , path. getName ( 0 ) ) ; //—>home
System . out . format ( «getNameCount: %d%n» , path. getNameCount ( ) ) ; //—>3
System . out . format ( «subpath(0,2): %d%n» , path. subpath ( 0 , 2 ) ) ;
System . out . format ( «getParent: %s%n» , path. getParent ( ) ) ; //—>/home/iam/
System . out . format ( «getRoot: %s%n» , path. getRoot ( ) ) ; //—>/
System . out . format ( «isHidden: %s%n» , path. isHidden ( ) ) ; //—>false
метод subpath остался без вывода не случайно. Он упорно не хочет работать ни в Win7 ни Ubuntu, о чем я сообщил куда надо. Хотя этот пример взят с оригинального туторала, а в прочем это не единственная ошибочка.
Файлы и атрибуты файлов. Управление метаданными.
public class Main <
* @param args the command line arguments
public static void main ( String [ ] args ) throws IOException <
// TODO code application logic here
Path file = Paths. get ( «/home/aum/Downloads/demotivatory_15.jpg» ) ;
BasicFileAttributes attr = Attributes . readBasicFileAttributes ( file ) ;
if ( attr. creationTime ( ) != null ) <
System . out . println ( «creationTime: » + attr. creationTime ( ) ) ;
if ( attr. lastAccessTime ( ) != null ) <
System . out . println ( «lastAccessTime: » + attr. lastAccessTime ( ) ) ;
if ( attr. lastModifiedTime ( ) != null ) <
System . out . println ( «lastModifiedTime: » + attr. lastModifiedTime ( ) ) ;
System . out . println ( «isDirectory: » + attr. isDirectory ( ) ) ;
System . out . println ( «isOther: » + attr. isOther ( ) ) ;
System . out . println ( «isRegularFile: » + attr. isRegularFile ( ) ) ;
System . out . println ( «isSymbolicLink: » + attr. isSymbolicLink ( ) ) ;
System . out . println ( «size: » + attr. size ( ) ) ;
Результат:
run:
lastAccessTime: 2011-02-14T14:16:32Z
lastModifiedTime: 2011-02-04T02:17:27Z
isDirectory: false
isOther: false
isRegularFile: true
isSymbolicLink: false
size: 64613
BUILD SUCCESSFUL (total time: 0 seconds)
На этом вводную предлагаю считать завершенной. За бортом осталось множество методов «синтаксической» работы с Path: удаление избыточности в пути, преобразование к абсолютному пути, сравнение путей, создание путей из объеденения и т.п. Всю необходимую информацию вы можете найти здесь (класс Path) И теперь мы смело можем перейти к более сложному, но и более интересному материалу.
Обход дерева файлов
Получение информации о папках и файлах на диске, довольно типичная задача для прикладных программ. Пакет java.nio.file предлагает нам удобное решение такой задачи, предоставляя интерфейс FileVisitor.
FileVisitor определяет требуемое поведение в ключевых точках прохождения процесса: когда файл посещен, прежде чем получить доступ к каталогу, после получения доступа к каталогу, или в случае отказа. Интерфейс состоит из пяти(! оставлю слово пять из оригинального текста, хотя как не старался нашел только 4! метода ) методов, которые соответствуют этим ситуациях:
- preVisitDirectory – вызывается до входа в папку
- postVisitDirectory – вызывается после «просмотра» всех объектов каталога. В случае возникновения ошибки, вызывается исключение и передается методу
- visitFile – вызывается для получения информации о файле, обрабатываемом в данный момент. В метод передаются атрибуты файла BasicFileAttributes, или мы можем передать определенный набор атрибутов, н-р можем выбрать чтение атрибутов DosFileAttributeView, чтобы определить является ли файл скрытым(«hidden»).
- visitFileFailed – вызывается при невозможности получить доступ к файлу. В этом случае вызывается исключение и передается методу. Обработка этого события может быть различной(вызов исключения, запись в лог или вывод информации на консоль и т.д.
import static java. nio . file . FileVisitResult . *;
//Используем класс SimpleFileVisitor, который реализовывает методы интерфейса FileVisitor
public class PrintFiles extends SimpleFileVisitor Path > <
//Выводим информацию о обрабатываемом в данный момент файле.
// метод Files.probeContentType выводит информацию о типе контента
public FileVisitResult visitFile ( Path file, BasicFileAttributes attr ) throws IOException <
if ( attr. isSymbolicLink ( ) ) <
System . out . format ( «Symbolic link: %s » , file ) ;
> else if ( attr. isRegularFile ( ) ) <
System . out . format ( «Regular file: %s Content is %s%n » , file,Files. probeContentType ( file ) ) ;
System . out . format ( «Other: %s » , file ) ;
System . out . println ( «(» + attr. size ( ) + «bytes)» ) ;
//Выводим информацию о посещенном каталоге
/* Перечисление FileVisitResult имеет следующие варианты
CONTINUE продолжить проход.
SKIP_SIBLINGS продолжить проход без осмотра дочерних папок.
SKIP_SUBTREE продолжить без просмотра объектов данной папки.
public FileVisitResult postVisitDirectory ( Path dir, IOException exc ) <
System . out . format ( «Directory: %s%n» , dir ) ;
//в случае ошибки доступа к файлу выбрасывается исключение IOException
public FileVisitResult visitFileFailed ( Path file, IOException exc ) <
System . err . println ( exc ) ;
public static void main ( String [ ] args ) throws IOException <
//создаем объект Path
Path startingDir = Paths. get ( «/home/aum/myjobs/» ) ;
//создаем экземпляр нашего класса, реализующего FileVisit
PrintFiles pf = new PrintFiles ( ) ;
//создаем экземпляр EnumSet, необходимый нам как параметр, и указывающий,
// что программа при прохождении дерева файлов, следует по ссылкам
EnumSet FileVisitOption > options = EnumSet. of ( FileVisitOption. FOLLOW_LINKS ) ;
int maxDepth = 2 ; //максимальное число уровней каталога для просмотра
/* Запуск анализа дерева файлов. Используется один из методов класса Files*/
Files. walkFileTree ( startingDir, options, maxDepth, pf ) ;
Результат
run:
Regular file: /home/aum/myjobs/sys.txt Content is text/plain
(11362bytes)
Regular file: /home/aum/myjobs/vzriv.mp3 Content is audio/mpeg
(2336827bytes)
Regular file: /home/aum/myjobs/report.html Content is text/html
(24574bytes)
Regular file: /home/aum/myjobs/examples.desktop Content is application/x-desktop
(179bytes)
Directory: /home/aum/myjobs/java
Directory: /home/aum/myjobs
BUILD SUCCESSFUL (total time: 0 seconds)
И в завершении о производительности. Н-р, код указаный выше, выполняется (на моем каталоге /home) так:
Objects found 19931 Total Size 2329851621 byte
BUILD SUCCESSFUL (total time: 38 seconds)
системные характеристики
Ubuntu 10.4
Kernel Linux 2.6.32-28
Gnom 2.30.2
Memory 1.9 G
Intel® Core(TM) i3 CPU M330 @ 2.13 GHz
Более полную информацию можно получить здесь
Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.
Path Operations
The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. This lesson addresses these Path methods, sometimes called syntactic operations, because they operate on the path itself and don’t access the file system.
This section covers the following:
Creating a Path
A Path instance contains the information used to specify the location of a file or directory. At the time it is defined, a Path is provided with a series of one or more names. A root element or a file name might be included, but neither are required. A Path might consist of just a single directory or file name.
You can easily create a Path object by using one of the following get methods from the Paths (note the plural) helper class:
The Paths.get method is shorthand for the following code:
The following example creates /u/joe/logs/foo.log assuming your home directory is /u/joe , or C:\joe\logs\foo.log if you are on Windows.
Retrieving Information about a Path
You can think of the Path as storing these name elements as a sequence. The highest element in the directory structure would be located at index 0. The lowest element in the directory structure would be located at index [n-1] , where n is the number of name elements in the Path . Methods are available for retrieving individual elements or a subsequence of the Path using these indexes.
The examples in this lesson use the following directory structure.
Sample Directory Structure
The following code snippet defines a Path instance and then invokes several methods to obtain information about the path:
Here is the output for both Windows and the Solaris OS:
Method Invoked | Returns in the Solaris OS | Returns in Microsoft Windows | Comment |
---|---|---|---|
toString | /home/joe/foo | C:\home\joe\foo | Returns the string representation of the Path . If the path was created using Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath ), the method performs minor syntactic cleanup. For example, in a UNIX operating system, it will correct the input string //home/joe/foo to /home/joe/foo . |
getFileName | foo | foo | Returns the file name or the last element of the sequence of name elements. |
getName(0) | home | home | Returns the path element corresponding to the specified index. The 0th element is the path element closest to the root. |
getNameCount | 3 | 3 | Returns the number of elements in the path. |
subpath(0,2) | home/joe | home\joe | Returns the subsequence of the Path (not including a root element) as specified by the beginning and ending indexes. |
getParent | /home/joe | \home\joe | Returns the path of the parent directory. |
getRoot | / | C:\ | Returns the root of the path. |
The previous example shows the output for an absolute path. In the following example, a relative path is specified:
Here is the output for Windows and the Solaris OS:
Method Invoked | Returns in the Solaris OS | Returns in Microsoft Windows |
---|---|---|
toString | sally/bar | sally\bar |
getFileName | bar | bar |
getName(0) | sally | sally |
getNameCount | 2 | 2 |
subpath(0,1) | sally | sally |
getParent | sally | sally |
getRoot | null | null |
Removing Redundancies From a Path
Many file systems use «.» notation to denote the current directory and «..» to denote the parent directory. You might have a situation where a Path contains redundant directory information. Perhaps a server is configured to save its log files in the » /dir/logs/. » directory, and you want to delete the trailing » /. » notation from the path.
The following examples both include redundancies:
The normalize method removes any redundant elements, which includes any » . » or » directory/.. » occurrences. Both of the preceding examples normalize to /home/joe/foo .
It is important to note that normalize doesn’t check at the file system when it cleans up a path. It is a purely syntactic operation. In the second example, if sally were a symbolic link, removing sally/.. might result in a Path that no longer locates the intended file.
To clean up a path while ensuring that the result locates the correct file, you can use the toRealPath method. This method is described in the next section, Converting a Path.
Converting a Path
You can use three methods to convert the Path . If you need to convert the path to a string that can be opened from a browser, you can use toUri . For example:
The toAbsolutePath method converts a path to an absolute path. If the passed-in path is already absolute, it returns the same Path object. The toAbsolutePath method can be very helpful when processing user-entered file names. For example:
The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not need to exist for this method to work.
The toRealPath method returns the real path of an existing file. This method performs several operations in one:
- If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
- If the Path is relative, it returns an absolute path.
- If the Path contains any redundant elements, it returns a path with those elements removed.
This method throws an exception if the file does not exist or cannot be accessed. You can catch the exception when you want to handle any of these cases. For example:
Joining Two Paths
You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.
For example, consider the following code snippet:
Passing an absolute path to the resolve method returns the passed-in path:
Creating a Path Between Two Paths
A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.
For example, consider two relative paths defined as joe and sally :
In the absence of any other information, it is assumed that joe and sally are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally , you would expect to first navigate one level up to the parent node and then down to sally :
Consider a slightly more complicated example:
In this example, the two paths share the same node, home . To navigate from home to bar , you first navigate one level down to sally and then one more level down to bar . Navigating from bar to home requires moving up two levels.
A relative path cannot be constructed if only one of the paths includes a root element. If both paths include a root element, the capability to construct a relative path is system dependent.
The recursive Copy example uses the relativize and resolve methods.
Comparing Two Paths
The Path class supports equals , enabling you to test two paths for equality. The startsWith and endsWith methods enable you to test whether a path begins or ends with a particular string. These methods are easy to use. For example:
The Path class implements the Iterable interface. The iterator method returns an object that enables you to iterate over the name elements in the path. The first element returned is that closest to the root in the directory tree. The following code snippet iterates over a path, printing each name element:
The Path class also implements the Comparable interface. You can compare Path objects by using compareTo which is useful for sorting.
You can also put Path objects into a Collection . See the Collections trail for more information about this powerful feature.
When you want to verify that two Path objects locate the same file, you can use the isSameFile method, as described in Checking Whether Two Paths Locate the Same File.