これは興味深いことです:android.jarのFile.createTempFile()メソッドがrt.jarのものとは異なって実装されているようです。 rt.jar内
(Javaの8で)、我々は持っている:TempDirectory.generateFile(String, String, File)
を使用しています
public static File createTempFile(String prefix, String suffix,
File directory)
throws IOException
{
if (prefix.length() < 3)
throw new IllegalArgumentException("Prefix string too short");
if (suffix == null)
suffix = ".tmp";
File tmpdir = (directory != null) ? directory
: TempDirectory.location();
SecurityManager sm = System.getSecurityManager();
File f;
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
if (sm != null) {
try {
sm.checkWrite(f.getPath());
} catch (SecurityException se) {
// don't reveal temporary directory location
if (directory == null)
throw new SecurityException("Unable to create temporary file");
throw se;
}
}
} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
if (!fs.createFileExclusively(f.getPath()))
throw new IOException("Unable to create temporary file");
return f;
}
:
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir)
throws IOException
{
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
// Use only the file name from the supplied prefix
prefix = (new File(prefix)).getName();
String name = prefix + Long.toString(n) + suffix;
File f = new File(dir, name);
if (!name.equals(f.getName()) || f.isInvalid()) {
if (System.getSecurityManager() != null)
throw new IOException("Unable to create temporary file");
else
throw new IOException("Unable to create temporary file, " + f);
}
return f;
}
これは、それらの正の乱数でファイル名につながります。 android.jar(AndroidのAPI 20)では
、我々は持っている:
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException {
// Force a prefix null check first
if (prefix.length() < 3) {
throw new IllegalArgumentException("prefix must be at least 3 characters");
}
if (suffix == null) {
suffix = ".tmp";
}
File tmpDirFile = directory;
if (tmpDirFile == null) {
String tmpDir = System.getProperty("java.io.tmpdir", ".");
tmpDirFile = new File(tmpDir);
}
File result;
do {
result = new File(tmpDirFile, prefix + tempFileRandom.nextInt() + suffix);
} while (!result.createNewFile());
return result;
}
tempFileRandom
が標準Random
インスタンスであるので、そのnextInt()
方法は、正だけでなく、負の整数を返します。
したがって、File.createTempFile()
を使用すると、Androidでマイナス記号/ハイフン付きのファイル名を返すことができます。
ベストプラクティスは、ランタイムライブラリで提供されているものに基づいて、独自のファイル名ジェネレータとcreateTempFile()
メソッドを実装することですが、正の乱数のみを使用します。
なぜ重要ですか?それが引き起こす特定の問題はありますか、それとも単に審美的に不快なものでしょうか? –
@Andy Turner: " - "記号は、Androidのファイル名の文字として受け入れられません。だから私は常に名前の名前を変更する必要があります。 –
@HansiHansenbaumそうです。 AndroidはLinuxです。受け入れられない文字は/とヌルターミネータだけです –