file separator java что такое
File separator java что такое
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".
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.
Русские Блоги
Кросс-платформенный File.separator для Java
Получите путь к хранилищу данных в соответствии со средой развертывания
в Windows Разделитель путей в Linux отличается от разделителя путей в Linux. Когда абсолютный путь используется напрямую, Кроссплатформенность Появится исключение «Нет такого файла или директории».
Например, чтобы создать файл test.txt во временном каталоге, он должен быть написан под Windows следующим образом:
File file1 = new File («C:\tmp\test.txt»);
в Linux выглядит так:
File file2 = new File («/tmp/test.txt»);
Если вы хотите рассмотреть кроссплатформенность, лучше всего написать следующее:
File myFile = new File(«C:» + File.separator + «tmp» + File.separator, «test.txt»);
Класс File имеет несколько статических полей, похожих на разделители, которые связаны с системой и должны использоваться как можно чаще во время программирования.
separatorChar
public static final char separatorChar
separator
public static final String separator
pathSeparatorChar
public static final char pathSeparatorChar
pathSeparator
public static final String pathSeparator
Разделитель путей, относящийся к системе, для удобства выражается в виде строки. Эта строка содержит только один символ, pathSeparatorChar.
проблема:
Это можно реализовать в моих локальных окнах, но нельзя реализовать в системах Linux:
причина:
Должно быть, что разделитель каталога неправильный при загрузке картинки. Каталог системы Windows использует \ в качестве разделителя, а каталог системы Linux является противоположностью Windows, в которой / используется в качестве разделителя.
File separator java что такое
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".
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.
Difference between File.separator and slash in paths
What is the difference between using File.separator and a normal / in a Java Path-String?
In contrast to double backslash \\ platform independence seems not to be the reason, since both versions work under Windows and Unix.
14 Answers 14
You use File.separator because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the «:» character as a file separator, and so dutifully the JVM obeys their wishes.
With the Java libraries for dealing with files, you can safely use / (slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.
You might want to use File.separator in UI, however, because it’s best to show people what will make sense in their OS, rather than what makes sense to Java.
Update: I have not been able, in five minutes of searching, to find the «you can always use a slash» behavior documented. Now, I’m sure I’ve seen it documented, but in the absense of finding an official reference (because my memory isn’t perfect), I’d stick with using File.separator because you know that will work.
Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a / with a : just like the windows jvm replaces it with a \ ).
However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.
OK let’s inspect some code.
File.java lines 428 to 435 in File. :
And let’s read fs/*(FileSystem)*/.fromURIPath() docs:
java.io.FileSystem
public abstract String fromURIPath(String path)
Post-process the given URI path string if necessary. This is used on win32, e.g., to transform «/c:/foo» into «c:/foo». The path string still has slash separators; code in the File class will translate them after this method returns.
This means FileSystem.fromURIPath() does post processing on URI path only in Windows, and because in the next line:
Well, there are more OS’s than Unix and Windows (Portable devices, etc), and Java is known for its portability. The best practice is to use it, so the JVM could determine which one is the best for that OS.
Although it doesn’t make much difference on the way in, it does on the way back.
Sure you can use either ‘/’ or ‘\’ in new File(String path), but File.getPath() will only give you one of them.
Late to the party. I’m on Windows 10 with JDK 1.8 and Eclipse MARS 1.
I find that
does not work. The last two are equivalent. So. I have good reason to NOT use File.separator.
portability plain and simple.
«Java SE8 for Programmers» claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:
will parse just fine. Take note of the last (Unix-style) separator.
It’s tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.
I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.
As the gentlemen described the difference with variant details.
I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.
The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.
Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is ‘/’, ‘\’ or ‘:’ for Unix, Windows, and Macintosh, respectively.
If you are using Java 7, checkout Path.resolve() and Paths.get().
Using File.separator made Ubuntu generate files with «\» on it’s name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use «/» every time to avoid files with «\» on it’s name
If you are trying to create a File from some ready path (saved in database, per example) using Linux separator, what should I do?
Maybe just use the path do create the file:
But Windows use a different separator ( \ ). So, is the alternative convert the slash separator to platform independent? Like:
This method convertPathToPlatformIndependent probably will have some kind of split by «/» and join with File.separator.
Well, for me, that’s not nice for a language that is platform independent (right?) and Java already support the use of / on Windows or Linux. But if you are working with paths and need to remember to this conversion every single time this will be a nightmare and you won’t have any real gain for the application on the future (maybe in the universe that @Pointy described).
System Properties
In Properties, we examined the way an application can use Properties objects to maintain its configuration. The Java platform itself uses a Properties object to maintain its own configuration. The System class maintains a Properties object that describes the configuration of the current working environment. System properties include information about the current user, the current version of the Java runtime, and the character used to separate components of a file path name.
The following table describes some of the most important system properties
Key | Meaning |
---|---|
«file.separator» | Character that separates components of a file path. This is » / » on UNIX and » \ » on Windows. |
«java.class.path» | Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property. |
«java.home» | Installation directory for Java Runtime Environment (JRE) |
«java.vendor» | JRE vendor name |
«java.vendor.url» | JRE vendor URL |
«java.version» | JRE version number |
«line.separator» | Sequence used by operating system to separate lines in text files |
«os.arch» | Operating system architecture |
«os.name» | Operating system name |
«os.version» | Operating system version |
«path.separator» | Path separator character used in java.class.path |
«user.dir» | User working directory |
«user.home» | User home directory |
«user.name» | User account name |
Reading System Properties
The getProperty method returns a string containing the value of the property. If the property does not exist, this version of getProperty returns null.
The last method provided by the System class to access property values is the getProperties method, which returns a Properties object. This object contains a complete set of system property definitions.
Writing System Properties
PropertiesTest then uses System.setProperties to install the new Properties objects as the current set of system properties.
Also note that the value of system properties can be overwritten! For example, if myProperties.txt contains the following line, the java.vendor system property will be overwritten:
In general, be careful not to overwrite system properties.
The setProperties method changes the set of system properties for the current running application. These changes are not persistent. That is, changing the system properties within an application will not affect future invocations of the Java interpreter for this or any other application. The runtime system re-initializes the system properties each time its starts up. If changes to system properties are to be persistent, then the application must write the values to some file before exiting and read them in again upon startup.