|/\- mainly those that...">

Identifying Invalid File Name Characters in Java 6 (Not 7!)

We now have a hard-coded character set that we check - :*?"<>|/\- mainly those that Windows complain about. However, working on Linux is too restrictive.

I know that in Java 7 NIO, the class Pathmust be smart enough to check this in an OS-dependent way, and throw InvalidPathExceptionif you specify an invalid file name. But we do not run Java 7. Is there a reliable way to do this in Java 6?

(Note that new File("foo:bar")on Windows, seems to be working. But what you actually get, if, for example, try FileWriterto write in your new File, it is an empty file named foo. exists()To Filereturn true at this point, but it is more or less lying.)

+3
source share
3 answers

Due to the lack of something clever, that’s what I came up with - his meat, anyway.

Strictly speaking, this is probably a combination of the OS and the file system that defines an invalid character set, but for my purposes, a hack based just on the OS seems to be good enough.

, , . Windows , XP NTFS - . Unix/Linux , , (, , ). MacOS : / , , - . ( , FAT NTFS.)

List<Integer> invalidIndices = new LinkedList<Integer>();

String invalidChars;
if (OS.isWindows()) {
    invalidChars = "\\/:*?\"<>|";
} else if (OS.isMacOSX()) {
    invalidChars = "/:";
} else { // assume Unix/Linux
    invalidChars = "/";
}

char[] chars = filename.toCharArray();
for (int i = 0; i < chars.length; i++) {
    if ((invalidChars.indexOf(chars[i]) >= 0) // OS-invalid
        || (chars[i] < '\u0020') // ctrls
        || (chars[i] > '\u007e' && chars[i] < '\u00a0') // ctrls
    ) {
        invalidIndices.add(i);
    }
}

return invalidIndices;

: SwingX OS, , - System.getProperty("os.name").

+5

File.getCanonicalPath() , .

.

+1

, Java7 "" ( , ) Java6?

, extends Path. , , Google CodeSearch ( ) GaePath.java, GaeVFS. , GaeVFS , Java7, Win32/UNIX/..., - ( ).

0

Source: https://habr.com/ru/post/1734899/


All Articles