File, Files, Path
— Привет, Амиго. Давно не виделись.
— Привет, Билаабо. О чем будешь рассказывать?
— Сегодня я расскажу о работе с файлами. В Java есть специальный класс (File), с помощью которого можно управлять файлами на диске компьютера. Для того чтобы управлять содержимым файлов, есть другие классы: FileInputStream, FileOutputStream,…
— Интересно. А когда ты говоришь «управлять файлами», что ты имеешь в виду?
— Как раз сейчас и расскажу. Файлы можно создавать, удалять, переименовывать и еще много чего. Практически во все классы, которые работают (читают, пишут, изменяют) с содержимым файла, можно передавать объект класса File. Пример:
— Но во втором случае длиннее же получается. Так и не понял – зачем эти файлы нужны.
— Для этого конкретного случая – да. Это не пример, как надо делать, а скорее – как можно.
Но вот представь, что тебе нужно вывести на экран список всех файлов, которые находятся в определенной директории (папке). Вот как это можно сделать с помощью файлов:
— listFiles() – это метод, который возвращает список файлов в папке с именем «c:/path/»?
— Да. Хотя программисты обычно говорят «директория» или «каталог». Название «папка» стало употребляться совсем недавно, но, в принципе, они все верные, и ты можешь говорить, как тебе удобнее.
— Ок. А getName() что делает? Выдает имя файла? И какое именно имя? Полное вместе с путем или только имя самого файла?
— Только имя самого файла. Для полного есть file.getAbsolutePath()
— А какие еще методы есть у класса File?
Метод | Описание |
---|---|
boolean isDirectory() | Является ли «объект файла» директорией |
boolean isFile() | Является ли объект файлом |
long length() | Возвращает размер/длину файла в байтах. |
boolean createNewFile() | Создает файл. Если такой файл уже был, возвращает false. |
boolean mkdir() | Создает директорию. Название mkdir происходит от «make directory». |
boolean mkdirs() | Создает директорию и все поддиректории. |
boolean delete() | Удаляет файл объекта на диске. Если объект – директория, то только, если в ней нет файлов. |
void deleteOnExit() | Добавляет файл в специальный список файлов, которые будут автоматически удалены при закрытии программы. |
File createTempFile( String prefix, String suffix, File directory) | Создает «временный файл» — файл с случайно сгенерированным уникальным именем – что-типа «dasd4d53sd». Дополнительные параметры – префикс к имени, суффикс (окончание). Если директория не указана, то файл создается в специальной директории ОС для временных файлов |
boolean exists() | Возвращает true, если файл с таким именем существует на диске компьютера. |
String getAbsolutePath() | Возвращает полный путь файла со всеми поддиректориями. |
String getCanonicalPath() | Возвращает канонический путь файла. Например, преобразовывает путь «c:/dir/dir2/../a.txt» к пути «c:/dir/a.txt» |
String[] list() | Возвращает массив имен файлов, которые содержатся в директории, которой является текущий объект-файл. |
File[] listFiles() | Возвращает массив файлов, которые содержатся в директории, которой является текущий объект-файл. |
long getTotalSpace() | Возвращает размер диска (количество байт) на котором расположен файл. |
long getFreeSpace() | Возвращает количество свободного места (количество байт) на диске, на котором расположен файл. |
boolean renameTo(File) | Переименовывает файл – содержимое файла фактически получает новое имя. Т.е. можно переименовать файл «c:/dir/a.txt» в «d:/out/text/b.doc». |
String getName() | Возвращает только имя файла, без пути. |
String getParent() | Возвращает только путь (директорию) к текущему файлу, без самого имени. |
Path toPath() | Возвращает объект Path, который соответствует текущему объекту File. |
— Ничего себе! А немаленький такой список получился. Да и вроде, можно довольно много сделать с помощью него: создавать, удалять файлы, переименовывать,…
А чтобы получить директорию текущего файла, надо вызвать getParent()?
— Ага, но он вернет не объект-файл, а строку – путь к файлу. Фактически у класса File почти все методы дублированы: одна версия возвращает String, вторая File. Вот смотри:
Если у тебя есть строка с путем к файлу, а надо объект File, то воспользуйся конструктором. Если же наоборот – есть объект File, а нужна строка – используй getAbsolutePath(). Пример:
— Отлично. Тогда вот тебе маленькое задание – выведи имена всех файлов, которые есть в той же директории, что и текущий файл.
— Нет ничего проще, вот, смотри:
— А то! Немного путает, что и для файла и для директории используется один и тот же класс – File. Как то это не очень логично, мне кажется.
— Так исторически сложилось. Раньше директория была специальным «пустым» файлом на диске. Сейчас уже, конечно, многое изменилось, но не везде. У меня на сегодня все.
Java windows file name
Related Articles
- Difficulty Level : Easy
- Last Updated : 17 Feb, 2021
The first lecture note given during java class is “In java file name and class name should be the same”. When the above law is violated a compiler error message will appear as below
Output:
But the myth can be violated in such a way to compile the above file.
Step 1:
Step 1 will create a Geeks.class (byte code) without any error message since the class is not public.
Step 2:
Now the output will be Hello world
The myth about the file name and class name should be same only when the class is declared in public.
The above program works as follows:
Now, this .class file can be executed. By the above features, some more miracles can be done. It is possible to have many classes in a java file. For debugging purposes, this approach can be used. Each class can be executed separately to test their functionalities(only on one condition: Inheritance concept should not be used).
But in general, it is good to follow the myth.
Example 1:
When the above file is compiled as javac Trial.java this will create 2 .class files as ForGeeks.class and GeeksTest.class .
Since each class has separate main() stub they can be tested individually.
- When java ForGeeks is executed the output is For Geeks class.
- When java GeeksTest is executed the output is Geeks Test class.
Example 2:
Note: There are two classes here, Triangle and Demo. Then which class name must be considered as the file name?
The class name Demo must be taken as the file name. The reason behind taking Demo as the file name is that it has the main method and execution begins from the main method.
This article is contributed by Sowmya.L.R. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Java windows file name
User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
- An optional system-dependent prefix string, such as a disk-drive specifier, «/» for the UNIX root directory, or «\\\\» for a Microsoft Windows UNC pathname, and
- A sequence of zero or more string names.
The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The empty abstract pathname has no prefix and an empty name sequence.
The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.
The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .
The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, as follows:
- For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
- For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.
A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
Validate a file name on Windows
Does this method guarantee a valid filename on Windows?
11 Answers 11
Given the requirements specified in the previously cited MSDN documentation, the following regex should do a pretty good job:
Note that this regex does not impose any limit on the length of the filename, but a real filename may be limited to 260 or 32767 chars depending on the platform.
Not enough,in Windows and DOS, some words might also be reserved and can not be used as filenames.
Windows usually limits file names to 260 characters. But the file name must actually be shorter than that, since the complete path (such as C:\Program Files\filename.txt) is included in this character count.
This is why you might occasionally encounter an error when copying a file with a very long file name to a location that has a longer path than its current location.
Well, I think the following method would guarantee a valid file name:
What do you think?
A method that guarantees, generally, that a Windows filename is valid — that it would be legal to create a file of that name — would be impossible to implement.
It is relatively straightforward to guarantee that a Windows filename is invalid. Some of the other regexes attempt to do this. However, the original question requests a stronger assertion: a method that guarantees the filename is valid on Windows.
The MSDN reference cited in other answers indicates that a Windows filename cannot contain «Any other character that the target file system does not allow». For instance, a file containing NUL would be invalid on some file systems, as would extended Unicode characters on some older file systems. Thus, a file called ☃.txt would be valid in some cases, but not others. So whether a hypothetical isValidName(\»☃\») would return true is dependent on the underlying file system.
Suppose, however, such a function is conservative and requires the filename consist of printable ASCII characters. All modern versions of Windows natively support NTFS, FAT32, and FAT16 file formats, which accept Unicode filenames. But drivers for arbitrary filesystems can be installed, and one is free to create a filesystem that doesn’t allow, for instance, the letter ‘n’. Thus, not even a simple file like «snowman.txt» can be «guaranteed» to be valid.
But even with extreme cases aside, there are other complications. For instance, a file named «$LogFile» cannot exist in the root of a NTFS volume, but can exist elsewhere on the volume. Thus, without knowing the directory, we cannot know if «$LogFile» is a valid name. But even «C:\data\$LogFile» might be invalid if, say, «c:\data\» is a symbolic link to another NTFS volume root. (Similarly, «D:\$LogFile» can be valid if D: is an alias to a subdirectory of an NTFS volume.)
There are even more complications. Alternate data streams on files, for instance, are legal on NTFS volumes, so «snowman.txt:☃» may be valid. All three major Windows file systems have path length restructions, so the validity of the file name is also function of the path. But the length of the physical path might not even be available to isValidName if the path is a virtual alias, mapped network drive, or symbolic link rather than a physical path on the volume.
Some others have suggested an alternative: create a file by the proposed name and then delete it, returning true if and only if the creation succeeds. This approach has several practical and theoretical problems. One, as indicated earlier, is that the validity is a function both of the filename and the path, so the validity of c:\test\☃.txt might differ from the validity of c:\test2\☃.txt. Also, the function would fail to write the file for any number of reasons not related to the validity of the file, such as not having write permission to the directory. A third flaw is that the validity of a filename is not required to be nondeterministic: a hypothetical file system might, for instance, not allow a deleted file to be replaced, or (in theory) could even randomly decide if a filename is valid.