| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.os; |
| 18 |
|
| 19 |
import static android.os.ParcelFileDescriptor.MODE_APPEND; |
| 20 |
import static android.os.ParcelFileDescriptor.MODE_CREATE; |
| 21 |
import static android.os.ParcelFileDescriptor.MODE_READ_ONLY; |
| 22 |
import static android.os.ParcelFileDescriptor.MODE_READ_WRITE; |
| 23 |
import static android.os.ParcelFileDescriptor.MODE_TRUNCATE; |
| 24 |
import static android.os.ParcelFileDescriptor.MODE_WRITE_ONLY; |
| 25 |
import static android.system.OsConstants.EINVAL; |
| 26 |
import static android.system.OsConstants.ENOSYS; |
| 27 |
import static android.system.OsConstants.F_OK; |
| 28 |
import static android.system.OsConstants.O_ACCMODE; |
| 29 |
import static android.system.OsConstants.O_APPEND; |
| 30 |
import static android.system.OsConstants.O_CREAT; |
| 31 |
import static android.system.OsConstants.O_RDONLY; |
| 32 |
import static android.system.OsConstants.O_RDWR; |
| 33 |
import static android.system.OsConstants.O_TRUNC; |
| 34 |
import static android.system.OsConstants.O_WRONLY; |
| 35 |
import static android.system.OsConstants.R_OK; |
| 36 |
import static android.system.OsConstants.SPLICE_F_MORE; |
| 37 |
import static android.system.OsConstants.SPLICE_F_MOVE; |
| 38 |
import static android.system.OsConstants.S_ISFIFO; |
| 39 |
import static android.system.OsConstants.S_ISREG; |
| 40 |
import static android.system.OsConstants.W_OK; |
| 41 |
|
| 42 |
import android.annotation.NonNull; |
| 43 |
import android.annotation.Nullable; |
| 44 |
import android.annotation.TestApi; |
| 45 |
import android.app.AppGlobals; |
| 46 |
import android.compat.annotation.UnsupportedAppUsage; |
| 47 |
import android.content.ContentResolver; |
| 48 |
import android.content.Context; |
| 49 |
import android.content.pm.PackageManager; |
| 50 |
import android.content.pm.ProviderInfo; |
| 51 |
import android.provider.DocumentsContract.Document; |
| 52 |
import android.provider.MediaStore; |
| 53 |
import android.system.ErrnoException; |
| 54 |
import android.system.Os; |
| 55 |
import android.system.StructStat; |
| 56 |
import android.text.TextUtils; |
| 57 |
import android.util.DataUnit; |
| 58 |
import android.util.Log; |
| 59 |
import android.util.Slog; |
| 60 |
import android.webkit.MimeTypeMap; |
| 61 |
|
| 62 |
import com.android.internal.annotations.VisibleForTesting; |
| 63 |
import com.android.internal.util.ArrayUtils; |
| 64 |
import com.android.internal.util.SizedInputStream; |
| 65 |
|
| 66 |
import libcore.io.IoUtils; |
| 67 |
import libcore.util.EmptyArray; |
| 68 |
|
| 69 |
import java.io.BufferedInputStream; |
| 70 |
import java.io.ByteArrayOutputStream; |
| 71 |
import java.io.File; |
| 72 |
import java.io.FileDescriptor; |
| 73 |
import java.io.FileInputStream; |
| 74 |
import java.io.FileNotFoundException; |
| 75 |
import java.io.FileOutputStream; |
| 76 |
import java.io.FilenameFilter; |
| 77 |
import java.io.IOException; |
| 78 |
import java.io.InputStream; |
| 79 |
import java.io.OutputStream; |
| 80 |
import java.nio.charset.StandardCharsets; |
| 81 |
import java.security.DigestInputStream; |
| 82 |
import java.security.MessageDigest; |
| 83 |
import java.security.NoSuchAlgorithmException; |
| 84 |
import java.util.Arrays; |
| 85 |
import java.util.Collection; |
| 86 |
import java.util.Comparator; |
| 87 |
import java.util.List; |
| 88 |
import java.util.Objects; |
| 89 |
import java.util.concurrent.Executor; |
| 90 |
import java.util.concurrent.TimeUnit; |
| 91 |
import java.util.regex.Pattern; |
| 92 |
import java.util.zip.CRC32; |
| 93 |
import java.util.zip.CheckedInputStream; |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
public final class FileUtils { |
| 99 |
private static final String TAG = "FileUtils"; |
| 100 |
|
| 101 |
public static final int S_IRWXU = 00700; |
| 102 |
public static final int S_IRUSR = 00400; |
| 103 |
public static final int S_IWUSR = 00200; |
| 104 |
public static final int S_IXUSR = 00100; |
| 105 |
|
| 106 |
public static final int S_IRWXG = 00070; |
| 107 |
public static final int S_IRGRP = 00040; |
| 108 |
public static final int S_IWGRP = 00020; |
| 109 |
public static final int S_IXGRP = 00010; |
| 110 |
|
| 111 |
public static final int S_IRWXO = 00007; |
| 112 |
public static final int S_IROTH = 00004; |
| 113 |
public static final int S_IWOTH = 00002; |
| 114 |
public static final int S_IXOTH = 00001; |
| 115 |
|
| 116 |
@UnsupportedAppUsage |
| 117 |
private FileUtils() { |
| 118 |
} |
| 119 |
|
| 120 |
private static final String CAMERA_DIR_LOWER_CASE = "/storage/emulated/" + UserHandle.myUserId() |
| 121 |
+ "/dcim/camera"; |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
private static class NoImagePreloadHolder { |
| 128 |
public static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[\\w%+,./=_-]+"); |
| 129 |
} |
| 130 |
|
| 131 |
|
| 132 |
private static boolean sEnableCopyOptimizations = true; |
| 133 |
private static volatile int sMediaProviderAppId = -1; |
| 134 |
|
| 135 |
private static final long COPY_CHECKPOINT_BYTES = 524288; |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
public interface ProgressListener { |
| 141 |
public void onProgress(long progress); |
| 142 |
} |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
@UnsupportedAppUsage |
| 154 |
public static int setPermissions(File path, int mode, int uid, int gid) { |
| 155 |
return setPermissions(path.getAbsolutePath(), mode, uid, gid); |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
@UnsupportedAppUsage |
| 168 |
public static int setPermissions(String path, int mode, int uid, int gid) { |
| 169 |
try { |
| 170 |
Os.chmod(path, mode); |
| 171 |
} catch (ErrnoException e) { |
| 172 |
Slog.w(TAG, "Failed to chmod(" + path + "): " + e); |
| 173 |
return e.errno; |
| 174 |
} |
| 175 |
|
| 176 |
if (uid >= 0 || gid >= 0) { |
| 177 |
try { |
| 178 |
Os.chown(path, uid, gid); |
| 179 |
} catch (ErrnoException e) { |
| 180 |
Slog.w(TAG, "Failed to chown(" + path + "): " + e); |
| 181 |
return e.errno; |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
return 0; |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 198 |
public static int setPermissions(FileDescriptor fd, int mode, int uid, int gid) { |
| 199 |
try { |
| 200 |
Os.fchmod(fd, mode); |
| 201 |
} catch (ErrnoException e) { |
| 202 |
Slog.w(TAG, "Failed to fchmod(): " + e); |
| 203 |
return e.errno; |
| 204 |
} |
| 205 |
|
| 206 |
if (uid >= 0 || gid >= 0) { |
| 207 |
try { |
| 208 |
Os.fchown(fd, uid, gid); |
| 209 |
} catch (ErrnoException e) { |
| 210 |
Slog.w(TAG, "Failed to fchown(): " + e); |
| 211 |
return e.errno; |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
return 0; |
| 216 |
} |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
public static void copyPermissions(@NonNull File from, @NonNull File to) throws IOException { |
| 226 |
try { |
| 227 |
final StructStat stat = Os.stat(from.getAbsolutePath()); |
| 228 |
Os.chmod(to.getAbsolutePath(), stat.st_mode); |
| 229 |
Os.chown(to.getAbsolutePath(), stat.st_uid, stat.st_gid); |
| 230 |
} catch (ErrnoException e) { |
| 231 |
throw e.rethrowAsIOException(); |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
@Deprecated |
| 240 |
public static int getUid(String path) { |
| 241 |
try { |
| 242 |
return Os.stat(path).st_uid; |
| 243 |
} catch (ErrnoException e) { |
| 244 |
return -1; |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
@UnsupportedAppUsage |
| 255 |
public static boolean sync(FileOutputStream stream) { |
| 256 |
try { |
| 257 |
if (stream != null) { |
| 258 |
stream.getFD().sync(); |
| 259 |
} |
| 260 |
return true; |
| 261 |
} catch (IOException e) { |
| 262 |
} |
| 263 |
return false; |
| 264 |
} |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
@UnsupportedAppUsage |
| 271 |
@Deprecated |
| 272 |
public static boolean copyFile(File srcFile, File destFile) { |
| 273 |
try { |
| 274 |
copyFileOrThrow(srcFile, destFile); |
| 275 |
return true; |
| 276 |
} catch (IOException e) { |
| 277 |
return false; |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
@Deprecated |
| 286 |
public static void copyFileOrThrow(File srcFile, File destFile) throws IOException { |
| 287 |
try (InputStream in = new FileInputStream(srcFile)) { |
| 288 |
copyToFileOrThrow(in, destFile); |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
@UnsupportedAppUsage |
| 297 |
@Deprecated |
| 298 |
public static boolean copyToFile(InputStream inputStream, File destFile) { |
| 299 |
try { |
| 300 |
copyToFileOrThrow(inputStream, destFile); |
| 301 |
return true; |
| 302 |
} catch (IOException e) { |
| 303 |
return false; |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
@Deprecated |
| 312 |
public static void copyToFileOrThrow(InputStream in, File destFile) throws IOException { |
| 313 |
if (destFile.exists()) { |
| 314 |
destFile.delete(); |
| 315 |
} |
| 316 |
try (FileOutputStream out = new FileOutputStream(destFile)) { |
| 317 |
copy(in, out); |
| 318 |
try { |
| 319 |
Os.fsync(out.getFD()); |
| 320 |
} catch (ErrnoException e) { |
| 321 |
throw e.rethrowAsIOException(); |
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
public static long copy(@NonNull File from, @NonNull File to) throws IOException { |
| 336 |
return copy(from, to, null, null, null); |
| 337 |
} |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
public static long copy(@NonNull File from, @NonNull File to, |
| 352 |
@Nullable CancellationSignal signal, @Nullable Executor executor, |
| 353 |
@Nullable ProgressListener listener) throws IOException { |
| 354 |
try (FileInputStream in = new FileInputStream(from); |
| 355 |
FileOutputStream out = new FileOutputStream(to)) { |
| 356 |
return copy(in, out, signal, executor, listener); |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
public static long copy(@NonNull InputStream in, @NonNull OutputStream out) throws IOException { |
| 369 |
return copy(in, out, null, null, null); |
| 370 |
} |
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
public static long copy(@NonNull InputStream in, @NonNull OutputStream out, |
| 384 |
@Nullable CancellationSignal signal, @Nullable Executor executor, |
| 385 |
@Nullable ProgressListener listener) throws IOException { |
| 386 |
if (sEnableCopyOptimizations) { |
| 387 |
if (in instanceof FileInputStream && out instanceof FileOutputStream) { |
| 388 |
return copy(((FileInputStream) in).getFD(), ((FileOutputStream) out).getFD(), |
| 389 |
signal, executor, listener); |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
|
| 394 |
return copyInternalUserspace(in, out, signal, executor, listener); |
| 395 |
} |
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out) |
| 406 |
throws IOException { |
| 407 |
return copy(in, out, null, null, null); |
| 408 |
} |
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out, |
| 422 |
@Nullable CancellationSignal signal, @Nullable Executor executor, |
| 423 |
@Nullable ProgressListener listener) throws IOException { |
| 424 |
return copy(in, out, Long.MAX_VALUE, signal, executor, listener); |
| 425 |
} |
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
|
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out, long count, |
| 441 |
@Nullable CancellationSignal signal, @Nullable Executor executor, |
| 442 |
@Nullable ProgressListener listener) throws IOException { |
| 443 |
if (sEnableCopyOptimizations) { |
| 444 |
try { |
| 445 |
final StructStat st_in = Os.fstat(in); |
| 446 |
final StructStat st_out = Os.fstat(out); |
| 447 |
if (S_ISREG(st_in.st_mode) && S_ISREG(st_out.st_mode)) { |
| 448 |
try { |
| 449 |
return copyInternalSendfile(in, out, count, signal, executor, listener); |
| 450 |
} catch (ErrnoException e) { |
| 451 |
if (e.errno == EINVAL || e.errno == ENOSYS) { |
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
return copyInternalUserspace(in, out, count, signal, executor, |
| 457 |
listener); |
| 458 |
} |
| 459 |
throw e; |
| 460 |
} |
| 461 |
} else if (S_ISFIFO(st_in.st_mode) || S_ISFIFO(st_out.st_mode)) { |
| 462 |
return copyInternalSplice(in, out, count, signal, executor, listener); |
| 463 |
} |
| 464 |
} catch (ErrnoException e) { |
| 465 |
throw e.rethrowAsIOException(); |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
|
| 470 |
return copyInternalUserspace(in, out, count, signal, executor, listener); |
| 471 |
} |
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
@VisibleForTesting |
| 479 |
public static long copyInternalSplice(FileDescriptor in, FileDescriptor out, long count, |
| 480 |
CancellationSignal signal, Executor executor, ProgressListener listener) |
| 481 |
throws ErrnoException { |
| 482 |
long progress = 0; |
| 483 |
long checkpoint = 0; |
| 484 |
|
| 485 |
long t; |
| 486 |
while ((t = Os.splice(in, null, out, null, Math.min(count, COPY_CHECKPOINT_BYTES), |
| 487 |
SPLICE_F_MOVE | SPLICE_F_MORE)) != 0) { |
| 488 |
progress += t; |
| 489 |
checkpoint += t; |
| 490 |
count -= t; |
| 491 |
|
| 492 |
if (checkpoint >= COPY_CHECKPOINT_BYTES) { |
| 493 |
if (signal != null) { |
| 494 |
signal.throwIfCanceled(); |
| 495 |
} |
| 496 |
if (executor != null && listener != null) { |
| 497 |
final long progressSnapshot = progress; |
| 498 |
executor.execute(() -> { |
| 499 |
listener.onProgress(progressSnapshot); |
| 500 |
}); |
| 501 |
} |
| 502 |
checkpoint = 0; |
| 503 |
} |
| 504 |
} |
| 505 |
if (executor != null && listener != null) { |
| 506 |
final long progressSnapshot = progress; |
| 507 |
executor.execute(() -> { |
| 508 |
listener.onProgress(progressSnapshot); |
| 509 |
}); |
| 510 |
} |
| 511 |
return progress; |
| 512 |
} |
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
@VisibleForTesting |
| 520 |
public static long copyInternalSendfile(FileDescriptor in, FileDescriptor out, long count, |
| 521 |
CancellationSignal signal, Executor executor, ProgressListener listener) |
| 522 |
throws ErrnoException { |
| 523 |
long progress = 0; |
| 524 |
long checkpoint = 0; |
| 525 |
|
| 526 |
long t; |
| 527 |
while ((t = Os.sendfile(out, in, null, Math.min(count, COPY_CHECKPOINT_BYTES))) != 0) { |
| 528 |
progress += t; |
| 529 |
checkpoint += t; |
| 530 |
count -= t; |
| 531 |
|
| 532 |
if (checkpoint >= COPY_CHECKPOINT_BYTES) { |
| 533 |
if (signal != null) { |
| 534 |
signal.throwIfCanceled(); |
| 535 |
} |
| 536 |
if (executor != null && listener != null) { |
| 537 |
final long progressSnapshot = progress; |
| 538 |
executor.execute(() -> { |
| 539 |
listener.onProgress(progressSnapshot); |
| 540 |
}); |
| 541 |
} |
| 542 |
checkpoint = 0; |
| 543 |
} |
| 544 |
} |
| 545 |
if (executor != null && listener != null) { |
| 546 |
final long progressSnapshot = progress; |
| 547 |
executor.execute(() -> { |
| 548 |
listener.onProgress(progressSnapshot); |
| 549 |
}); |
| 550 |
} |
| 551 |
return progress; |
| 552 |
} |
| 553 |
|
| 554 |
|
| 555 |
@Deprecated |
| 556 |
@VisibleForTesting |
| 557 |
public static long copyInternalUserspace(FileDescriptor in, FileDescriptor out, |
| 558 |
ProgressListener listener, CancellationSignal signal, long count) |
| 559 |
throws IOException { |
| 560 |
return copyInternalUserspace(in, out, count, signal, Runnable::run, listener); |
| 561 |
} |
| 562 |
|
| 563 |
|
| 564 |
@VisibleForTesting |
| 565 |
public static long copyInternalUserspace(FileDescriptor in, FileDescriptor out, long count, |
| 566 |
CancellationSignal signal, Executor executor, ProgressListener listener) |
| 567 |
throws IOException { |
| 568 |
if (count != Long.MAX_VALUE) { |
| 569 |
return copyInternalUserspace(new SizedInputStream(new FileInputStream(in), count), |
| 570 |
new FileOutputStream(out), signal, executor, listener); |
| 571 |
} else { |
| 572 |
return copyInternalUserspace(new FileInputStream(in), |
| 573 |
new FileOutputStream(out), signal, executor, listener); |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
|
| 578 |
@VisibleForTesting |
| 579 |
public static long copyInternalUserspace(InputStream in, OutputStream out, |
| 580 |
CancellationSignal signal, Executor executor, ProgressListener listener) |
| 581 |
throws IOException { |
| 582 |
long progress = 0; |
| 583 |
long checkpoint = 0; |
| 584 |
byte[] buffer = new byte[8192]; |
| 585 |
|
| 586 |
int t; |
| 587 |
while ((t = in.read(buffer)) != -1) { |
| 588 |
out.write(buffer, 0, t); |
| 589 |
|
| 590 |
progress += t; |
| 591 |
checkpoint += t; |
| 592 |
|
| 593 |
if (checkpoint >= COPY_CHECKPOINT_BYTES) { |
| 594 |
if (signal != null) { |
| 595 |
signal.throwIfCanceled(); |
| 596 |
} |
| 597 |
if (executor != null && listener != null) { |
| 598 |
final long progressSnapshot = progress; |
| 599 |
executor.execute(() -> { |
| 600 |
listener.onProgress(progressSnapshot); |
| 601 |
}); |
| 602 |
} |
| 603 |
checkpoint = 0; |
| 604 |
} |
| 605 |
} |
| 606 |
if (executor != null && listener != null) { |
| 607 |
final long progressSnapshot = progress; |
| 608 |
executor.execute(() -> { |
| 609 |
listener.onProgress(progressSnapshot); |
| 610 |
}); |
| 611 |
} |
| 612 |
return progress; |
| 613 |
} |
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
@UnsupportedAppUsage |
| 621 |
public static boolean isFilenameSafe(File file) { |
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
return NoImagePreloadHolder.SAFE_FILENAME_PATTERN.matcher(file.getPath()).matches(); |
| 626 |
} |
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
@UnsupportedAppUsage |
| 638 |
public static String readTextFile(File file, int max, String ellipsis) throws IOException { |
| 639 |
InputStream input = new FileInputStream(file); |
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
BufferedInputStream bis = new BufferedInputStream(input); |
| 644 |
try { |
| 645 |
long size = file.length(); |
| 646 |
if (max > 0 || (size > 0 && max == 0)) { |
| 647 |
if (size > 0 && (max == 0 || size < max)) max = (int) size; |
| 648 |
byte[] data = new byte[max + 1]; |
| 649 |
int length = bis.read(data); |
| 650 |
if (length <= 0) return ""; |
| 651 |
if (length <= max) return new String(data, 0, length); |
| 652 |
if (ellipsis == null) return new String(data, 0, max); |
| 653 |
return new String(data, 0, max) + ellipsis; |
| 654 |
} else if (max < 0) { |
| 655 |
int len; |
| 656 |
boolean rolled = false; |
| 657 |
byte[] last = null; |
| 658 |
byte[] data = null; |
| 659 |
do { |
| 660 |
if (last != null) rolled = true; |
| 661 |
byte[] tmp = last; last = data; data = tmp; |
| 662 |
if (data == null) data = new byte[-max]; |
| 663 |
len = bis.read(data); |
| 664 |
} while (len == data.length); |
| 665 |
|
| 666 |
if (last == null && len <= 0) return ""; |
| 667 |
if (last == null) return new String(data, 0, len); |
| 668 |
if (len > 0) { |
| 669 |
rolled = true; |
| 670 |
System.arraycopy(last, len, last, 0, last.length - len); |
| 671 |
System.arraycopy(data, 0, last, last.length - len, len); |
| 672 |
} |
| 673 |
if (ellipsis == null || !rolled) return new String(last); |
| 674 |
return ellipsis + new String(last); |
| 675 |
} else { |
| 676 |
ByteArrayOutputStream contents = new ByteArrayOutputStream(); |
| 677 |
int len; |
| 678 |
byte[] data = new byte[1024]; |
| 679 |
do { |
| 680 |
len = bis.read(data); |
| 681 |
if (len > 0) contents.write(data, 0, len); |
| 682 |
} while (len == data.length); |
| 683 |
return contents.toString(); |
| 684 |
} |
| 685 |
} finally { |
| 686 |
bis.close(); |
| 687 |
input.close(); |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
|
| 692 |
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 693 |
public static void stringToFile(File file, String string) throws IOException { |
| 694 |
stringToFile(file.getAbsolutePath(), string); |
| 695 |
} |
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
public static void bytesToFile(String filename, byte[] content) throws IOException { |
| 704 |
if (filename.startsWith("/proc/")) { |
| 705 |
final int oldMask = StrictMode.allowThreadDiskWritesMask(); |
| 706 |
try (FileOutputStream fos = new FileOutputStream(filename)) { |
| 707 |
fos.write(content); |
| 708 |
} finally { |
| 709 |
StrictMode.setThreadPolicyMask(oldMask); |
| 710 |
} |
| 711 |
} else { |
| 712 |
try (FileOutputStream fos = new FileOutputStream(filename)) { |
| 713 |
fos.write(content); |
| 714 |
} |
| 715 |
} |
| 716 |
} |
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
@UnsupportedAppUsage |
| 727 |
public static void stringToFile(String filename, String string) throws IOException { |
| 728 |
bytesToFile(filename, string.getBytes(StandardCharsets.UTF_8)); |
| 729 |
} |
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 742 |
@Deprecated |
| 743 |
public static long checksumCrc32(File file) throws FileNotFoundException, IOException { |
| 744 |
CRC32 checkSummer = new CRC32(); |
| 745 |
CheckedInputStream cis = null; |
| 746 |
|
| 747 |
try { |
| 748 |
cis = new CheckedInputStream( new FileInputStream(file), checkSummer); |
| 749 |
byte[] buf = new byte[128]; |
| 750 |
while(cis.read(buf) >= 0) { |
| 751 |
|
| 752 |
} |
| 753 |
return checkSummer.getValue(); |
| 754 |
} finally { |
| 755 |
if (cis != null) { |
| 756 |
try { |
| 757 |
cis.close(); |
| 758 |
} catch (IOException e) { |
| 759 |
} |
| 760 |
} |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
@TestApi |
| 772 |
@NonNull |
| 773 |
public static byte[] digest(@NonNull File file, @NonNull String algorithm) |
| 774 |
throws IOException, NoSuchAlgorithmException { |
| 775 |
try (FileInputStream in = new FileInputStream(file)) { |
| 776 |
return digest(in, algorithm); |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
@TestApi |
| 788 |
@NonNull |
| 789 |
public static byte[] digest(@NonNull InputStream in, @NonNull String algorithm) |
| 790 |
throws IOException, NoSuchAlgorithmException { |
| 791 |
|
| 792 |
return digestInternalUserspace(in, algorithm); |
| 793 |
} |
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
public static byte[] digest(FileDescriptor fd, String algorithm) |
| 803 |
throws IOException, NoSuchAlgorithmException { |
| 804 |
|
| 805 |
return digestInternalUserspace(new FileInputStream(fd), algorithm); |
| 806 |
} |
| 807 |
|
| 808 |
private static byte[] digestInternalUserspace(InputStream in, String algorithm) |
| 809 |
throws IOException, NoSuchAlgorithmException { |
| 810 |
final MessageDigest digest = MessageDigest.getInstance(algorithm); |
| 811 |
try (DigestInputStream digestStream = new DigestInputStream(in, digest)) { |
| 812 |
final byte[] buffer = new byte[8192]; |
| 813 |
while (digestStream.read(buffer) != -1) { |
| 814 |
} |
| 815 |
} |
| 816 |
return digest.digest(); |
| 817 |
} |
| 818 |
|
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 829 |
public static boolean deleteOlderFiles(File dir, int minCount, long minAgeMs) { |
| 830 |
if (minCount < 0 || minAgeMs < 0) { |
| 831 |
throw new IllegalArgumentException("Constraints must be positive or 0"); |
| 832 |
} |
| 833 |
|
| 834 |
final File[] files = dir.listFiles(); |
| 835 |
if (files == null) return false; |
| 836 |
|
| 837 |
|
| 838 |
Arrays.sort(files, new Comparator<File>() { |
| 839 |
@Override |
| 840 |
public int compare(File lhs, File rhs) { |
| 841 |
return Long.compare(rhs.lastModified(), lhs.lastModified()); |
| 842 |
} |
| 843 |
}); |
| 844 |
|
| 845 |
|
| 846 |
boolean deleted = false; |
| 847 |
for (int i = minCount; i < files.length; i++) { |
| 848 |
final File file = files[i]; |
| 849 |
|
| 850 |
|
| 851 |
final long age = System.currentTimeMillis() - file.lastModified(); |
| 852 |
if (age > minAgeMs) { |
| 853 |
if (file.delete()) { |
| 854 |
Log.d(TAG, "Deleted old file " + file); |
| 855 |
deleted = true; |
| 856 |
} |
| 857 |
} |
| 858 |
} |
| 859 |
return deleted; |
| 860 |
} |
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
public static boolean contains(File[] dirs, File file) { |
| 873 |
for (File dir : dirs) { |
| 874 |
if (contains(dir, file)) { |
| 875 |
return true; |
| 876 |
} |
| 877 |
} |
| 878 |
return false; |
| 879 |
} |
| 880 |
|
| 881 |
|
| 882 |
public static boolean contains(Collection<File> dirs, File file) { |
| 883 |
for (File dir : dirs) { |
| 884 |
if (contains(dir, file)) { |
| 885 |
return true; |
| 886 |
} |
| 887 |
} |
| 888 |
return false; |
| 889 |
} |
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
@TestApi |
| 902 |
public static boolean contains(File dir, File file) { |
| 903 |
if (dir == null || file == null) return false; |
| 904 |
return contains(dir.getAbsolutePath(), file.getAbsolutePath()); |
| 905 |
} |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
public static boolean contains(String dirPath, String filePath) { |
| 918 |
if (dirPath.equals(filePath)) { |
| 919 |
return true; |
| 920 |
} |
| 921 |
if (!dirPath.endsWith("/")) { |
| 922 |
dirPath += "/"; |
| 923 |
} |
| 924 |
return filePath.startsWith(dirPath); |
| 925 |
} |
| 926 |
|
| 927 |
|
| 928 |
public static boolean deleteContentsAndDir(File dir) { |
| 929 |
if (deleteContents(dir)) { |
| 930 |
return dir.delete(); |
| 931 |
} else { |
| 932 |
return false; |
| 933 |
} |
| 934 |
} |
| 935 |
|
| 936 |
|
| 937 |
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 938 |
public static boolean deleteContents(File dir) { |
| 939 |
File[] files = dir.listFiles(); |
| 940 |
boolean success = true; |
| 941 |
if (files != null) { |
| 942 |
for (File file : files) { |
| 943 |
if (file.isDirectory()) { |
| 944 |
success &= deleteContents(file); |
| 945 |
} |
| 946 |
if (!file.delete()) { |
| 947 |
Log.w(TAG, "Failed to delete " + file); |
| 948 |
success = false; |
| 949 |
} |
| 950 |
} |
| 951 |
} |
| 952 |
return success; |
| 953 |
} |
| 954 |
|
| 955 |
private static boolean isValidExtFilenameChar(char c) { |
| 956 |
switch (c) { |
| 957 |
case '\0': |
| 958 |
case '/': |
| 959 |
return false; |
| 960 |
default: |
| 961 |
return true; |
| 962 |
} |
| 963 |
} |
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
public static boolean isValidExtFilename(String name) { |
| 971 |
return (name != null) && name.equals(buildValidExtFilename(name)); |
| 972 |
} |
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
public static String buildValidExtFilename(String name) { |
| 981 |
if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) { |
| 982 |
return "(invalid)"; |
| 983 |
} |
| 984 |
final StringBuilder res = new StringBuilder(name.length()); |
| 985 |
for (int i = 0; i < name.length(); i++) { |
| 986 |
final char c = name.charAt(i); |
| 987 |
if (isValidExtFilenameChar(c)) { |
| 988 |
res.append(c); |
| 989 |
} else { |
| 990 |
res.append('_'); |
| 991 |
} |
| 992 |
} |
| 993 |
trimFilename(res, 255); |
| 994 |
return res.toString(); |
| 995 |
} |
| 996 |
|
| 997 |
private static boolean isValidFatFilenameChar(char c) { |
| 998 |
if ((0x00 <= c && c <= 0x1f)) { |
| 999 |
return false; |
| 1000 |
} |
| 1001 |
switch (c) { |
| 1002 |
case '"': |
| 1003 |
case '*': |
| 1004 |
case '/': |
| 1005 |
case ':': |
| 1006 |
case '<': |
| 1007 |
case '>': |
| 1008 |
case '?': |
| 1009 |
case '\\': |
| 1010 |
case '|': |
| 1011 |
case 0x7F: |
| 1012 |
return false; |
| 1013 |
default: |
| 1014 |
return true; |
| 1015 |
} |
| 1016 |
} |
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
|
| 1023 |
public static boolean isValidFatFilename(String name) { |
| 1024 |
return (name != null) && name.equals(buildValidFatFilename(name)); |
| 1025 |
} |
| 1026 |
|
| 1027 |
|
| 1028 |
|
| 1029 |
|
| 1030 |
|
| 1031 |
|
| 1032 |
|
| 1033 |
public static String buildValidFatFilename(String name) { |
| 1034 |
if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) { |
| 1035 |
return "(invalid)"; |
| 1036 |
} |
| 1037 |
final StringBuilder res = new StringBuilder(name.length()); |
| 1038 |
for (int i = 0; i < name.length(); i++) { |
| 1039 |
final char c = name.charAt(i); |
| 1040 |
if (isValidFatFilenameChar(c)) { |
| 1041 |
res.append(c); |
| 1042 |
} else { |
| 1043 |
res.append('_'); |
| 1044 |
} |
| 1045 |
} |
| 1046 |
|
| 1047 |
|
| 1048 |
trimFilename(res, 255); |
| 1049 |
return res.toString(); |
| 1050 |
} |
| 1051 |
|
| 1052 |
|
| 1053 |
@VisibleForTesting |
| 1054 |
public static String trimFilename(String str, int maxBytes) { |
| 1055 |
final StringBuilder res = new StringBuilder(str); |
| 1056 |
trimFilename(res, maxBytes); |
| 1057 |
return res.toString(); |
| 1058 |
} |
| 1059 |
|
| 1060 |
|
| 1061 |
private static void trimFilename(StringBuilder res, int maxBytes) { |
| 1062 |
byte[] raw = res.toString().getBytes(StandardCharsets.UTF_8); |
| 1063 |
if (raw.length > maxBytes) { |
| 1064 |
maxBytes -= 3; |
| 1065 |
while (raw.length > maxBytes) { |
| 1066 |
res.deleteCharAt(res.length() / 2); |
| 1067 |
raw = res.toString().getBytes(StandardCharsets.UTF_8); |
| 1068 |
} |
| 1069 |
res.insert(res.length() / 2, "..."); |
| 1070 |
} |
| 1071 |
} |
| 1072 |
|
| 1073 |
|
| 1074 |
public static String rewriteAfterRename(File beforeDir, File afterDir, String path) { |
| 1075 |
if (path == null) return null; |
| 1076 |
final File result = rewriteAfterRename(beforeDir, afterDir, new File(path)); |
| 1077 |
return (result != null) ? result.getAbsolutePath() : null; |
| 1078 |
} |
| 1079 |
|
| 1080 |
|
| 1081 |
public static String[] rewriteAfterRename(File beforeDir, File afterDir, String[] paths) { |
| 1082 |
if (paths == null) return null; |
| 1083 |
final String[] result = new String[paths.length]; |
| 1084 |
for (int i = 0; i < paths.length; i++) { |
| 1085 |
result[i] = rewriteAfterRename(beforeDir, afterDir, paths[i]); |
| 1086 |
} |
| 1087 |
return result; |
| 1088 |
} |
| 1089 |
|
| 1090 |
|
| 1091 |
|
| 1092 |
|
| 1093 |
|
| 1094 |
|
| 1095 |
|
| 1096 |
|
| 1097 |
public static File rewriteAfterRename(File beforeDir, File afterDir, File file) { |
| 1098 |
if (file == null || beforeDir == null || afterDir == null) return null; |
| 1099 |
if (contains(beforeDir, file)) { |
| 1100 |
final String splice = file.getAbsolutePath().substring( |
| 1101 |
beforeDir.getAbsolutePath().length()); |
| 1102 |
return new File(afterDir, splice); |
| 1103 |
} |
| 1104 |
return null; |
| 1105 |
} |
| 1106 |
|
| 1107 |
|
| 1108 |
private static File buildUniqueFileWithExtension(File parent, String name, String ext) |
| 1109 |
throws FileNotFoundException { |
| 1110 |
File file = buildFile(parent, name, ext); |
| 1111 |
|
| 1112 |
|
| 1113 |
int n = 0; |
| 1114 |
while (file.exists()) { |
| 1115 |
if (n++ >= 32) { |
| 1116 |
throw new FileNotFoundException("Failed to create unique file"); |
| 1117 |
} |
| 1118 |
file = buildFile(parent, name + " (" + n + ")", ext); |
| 1119 |
} |
| 1120 |
|
| 1121 |
return file; |
| 1122 |
} |
| 1123 |
|
| 1124 |
|
| 1125 |
|
| 1126 |
|
| 1127 |
|
| 1128 |
|
| 1129 |
|
| 1130 |
|
| 1131 |
|
| 1132 |
|
| 1133 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
public static File buildUniqueFile(File parent, String mimeType, String displayName) |
| 1137 |
throws FileNotFoundException { |
| 1138 |
final String[] parts = splitFileName(mimeType, displayName); |
| 1139 |
return buildUniqueFileWithExtension(parent, parts[0], parts[1]); |
| 1140 |
} |
| 1141 |
|
| 1142 |
|
| 1143 |
public static File buildNonUniqueFile(File parent, String mimeType, String displayName) { |
| 1144 |
final String[] parts = splitFileName(mimeType, displayName); |
| 1145 |
return buildFile(parent, parts[0], parts[1]); |
| 1146 |
} |
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
public static File buildUniqueFile(File parent, String displayName) |
| 1155 |
throws FileNotFoundException { |
| 1156 |
final String name; |
| 1157 |
final String ext; |
| 1158 |
|
| 1159 |
|
| 1160 |
final int lastDot = displayName.lastIndexOf('.'); |
| 1161 |
if (lastDot >= 0) { |
| 1162 |
name = displayName.substring(0, lastDot); |
| 1163 |
ext = displayName.substring(lastDot + 1); |
| 1164 |
} else { |
| 1165 |
name = displayName; |
| 1166 |
ext = null; |
| 1167 |
} |
| 1168 |
|
| 1169 |
return buildUniqueFileWithExtension(parent, name, ext); |
| 1170 |
} |
| 1171 |
|
| 1172 |
|
| 1173 |
|
| 1174 |
|
| 1175 |
|
| 1176 |
|
| 1177 |
|
| 1178 |
|
| 1179 |
|
| 1180 |
public static String[] splitFileName(String mimeType, String displayName) { |
| 1181 |
String name; |
| 1182 |
String ext; |
| 1183 |
|
| 1184 |
if (Document.MIME_TYPE_DIR.equals(mimeType)) { |
| 1185 |
name = displayName; |
| 1186 |
ext = null; |
| 1187 |
} else { |
| 1188 |
String mimeTypeFromExt; |
| 1189 |
|
| 1190 |
|
| 1191 |
final int lastDot = displayName.lastIndexOf('.'); |
| 1192 |
if (lastDot >= 0) { |
| 1193 |
name = displayName.substring(0, lastDot); |
| 1194 |
ext = displayName.substring(lastDot + 1); |
| 1195 |
mimeTypeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension( |
| 1196 |
ext.toLowerCase()); |
| 1197 |
} else { |
| 1198 |
name = displayName; |
| 1199 |
ext = null; |
| 1200 |
mimeTypeFromExt = null; |
| 1201 |
} |
| 1202 |
|
| 1203 |
if (mimeTypeFromExt == null) { |
| 1204 |
mimeTypeFromExt = ContentResolver.MIME_TYPE_DEFAULT; |
| 1205 |
} |
| 1206 |
|
| 1207 |
final String extFromMimeType; |
| 1208 |
if (ContentResolver.MIME_TYPE_DEFAULT.equals(mimeType)) { |
| 1209 |
extFromMimeType = null; |
| 1210 |
} else { |
| 1211 |
extFromMimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); |
| 1212 |
} |
| 1213 |
|
| 1214 |
if (Objects.equals(mimeType, mimeTypeFromExt) || Objects.equals(ext, extFromMimeType)) { |
| 1215 |
|
| 1216 |
} else { |
| 1217 |
|
| 1218 |
name = displayName; |
| 1219 |
ext = extFromMimeType; |
| 1220 |
} |
| 1221 |
} |
| 1222 |
|
| 1223 |
if (ext == null) { |
| 1224 |
ext = ""; |
| 1225 |
} |
| 1226 |
|
| 1227 |
return new String[] { name, ext }; |
| 1228 |
} |
| 1229 |
|
| 1230 |
|
| 1231 |
private static File buildFile(File parent, String name, String ext) { |
| 1232 |
if (TextUtils.isEmpty(ext)) { |
| 1233 |
return new File(parent, name); |
| 1234 |
} else { |
| 1235 |
return new File(parent, name + "." + ext); |
| 1236 |
} |
| 1237 |
} |
| 1238 |
|
| 1239 |
|
| 1240 |
public static @NonNull String[] listOrEmpty(@Nullable File dir) { |
| 1241 |
return (dir != null) ? ArrayUtils.defeatNullable(dir.list()) |
| 1242 |
: EmptyArray.STRING; |
| 1243 |
} |
| 1244 |
|
| 1245 |
|
| 1246 |
public static @NonNull File[] listFilesOrEmpty(@Nullable File dir) { |
| 1247 |
return (dir != null) ? ArrayUtils.defeatNullable(dir.listFiles()) |
| 1248 |
: ArrayUtils.EMPTY_FILE; |
| 1249 |
} |
| 1250 |
|
| 1251 |
|
| 1252 |
public static @NonNull File[] listFilesOrEmpty(@Nullable File dir, FilenameFilter filter) { |
| 1253 |
return (dir != null) ? ArrayUtils.defeatNullable(dir.listFiles(filter)) |
| 1254 |
: ArrayUtils.EMPTY_FILE; |
| 1255 |
} |
| 1256 |
|
| 1257 |
|
| 1258 |
public static @Nullable File newFileOrNull(@Nullable String path) { |
| 1259 |
return (path != null) ? new File(path) : null; |
| 1260 |
} |
| 1261 |
|
| 1262 |
|
| 1263 |
|
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
|
| 1268 |
|
| 1269 |
public static @Nullable File createDir(File baseDir, String name) { |
| 1270 |
final File dir = new File(baseDir, name); |
| 1271 |
|
| 1272 |
return createDir(dir) ? dir : null; |
| 1273 |
} |
| 1274 |
|
| 1275 |
|
| 1276 |
|
| 1277 |
|
| 1278 |
|
| 1279 |
|
| 1280 |
|
| 1281 |
|
| 1282 |
public static boolean createDir(File dir) { |
| 1283 |
if (dir.mkdir()) { |
| 1284 |
return true; |
| 1285 |
} |
| 1286 |
|
| 1287 |
if (dir.exists()) { |
| 1288 |
return dir.isDirectory(); |
| 1289 |
} |
| 1290 |
|
| 1291 |
return false; |
| 1292 |
} |
| 1293 |
|
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
public static long roundStorageSize(long size) { |
| 1302 |
long val = 1; |
| 1303 |
long pow = 1; |
| 1304 |
while ((val * pow) < size) { |
| 1305 |
val <<= 1; |
| 1306 |
if (val > 512) { |
| 1307 |
val = 1; |
| 1308 |
pow *= 1000; |
| 1309 |
} |
| 1310 |
} |
| 1311 |
return val * pow; |
| 1312 |
} |
| 1313 |
|
| 1314 |
private static long toBytes(long value, String unit) { |
| 1315 |
unit = unit.toUpperCase(); |
| 1316 |
|
| 1317 |
if (List.of("B").contains(unit)) { |
| 1318 |
return value; |
| 1319 |
} |
| 1320 |
|
| 1321 |
if (List.of("K", "KB").contains(unit)) { |
| 1322 |
return DataUnit.KILOBYTES.toBytes(value); |
| 1323 |
} |
| 1324 |
|
| 1325 |
if (List.of("M", "MB").contains(unit)) { |
| 1326 |
return DataUnit.MEGABYTES.toBytes(value); |
| 1327 |
} |
| 1328 |
|
| 1329 |
if (List.of("G", "GB").contains(unit)) { |
| 1330 |
return DataUnit.GIGABYTES.toBytes(value); |
| 1331 |
} |
| 1332 |
|
| 1333 |
if (List.of("KI", "KIB").contains(unit)) { |
| 1334 |
return DataUnit.KIBIBYTES.toBytes(value); |
| 1335 |
} |
| 1336 |
|
| 1337 |
if (List.of("MI", "MIB").contains(unit)) { |
| 1338 |
return DataUnit.MEBIBYTES.toBytes(value); |
| 1339 |
} |
| 1340 |
|
| 1341 |
if (List.of("GI", "GIB").contains(unit)) { |
| 1342 |
return DataUnit.GIBIBYTES.toBytes(value); |
| 1343 |
} |
| 1344 |
|
| 1345 |
return Long.MIN_VALUE; |
| 1346 |
} |
| 1347 |
|
| 1348 |
|
| 1349 |
|
| 1350 |
|
| 1351 |
|
| 1352 |
|
| 1353 |
|
| 1354 |
|
| 1355 |
|
| 1356 |
|
| 1357 |
|
| 1358 |
|
| 1359 |
|
| 1360 |
public static long parseSize(@Nullable String fmtSize) { |
| 1361 |
if (fmtSize == null || fmtSize.isBlank()) { |
| 1362 |
return Long.MIN_VALUE; |
| 1363 |
} |
| 1364 |
|
| 1365 |
int sign = 1; |
| 1366 |
fmtSize = fmtSize.trim(); |
| 1367 |
char first = fmtSize.charAt(0); |
| 1368 |
if (first == '-' || first == '+') { |
| 1369 |
if (first == '-') { |
| 1370 |
sign = -1; |
| 1371 |
} |
| 1372 |
|
| 1373 |
fmtSize = fmtSize.replace(first + "", ""); |
| 1374 |
} |
| 1375 |
|
| 1376 |
int index = 0; |
| 1377 |
|
| 1378 |
while (index < fmtSize.length() && Character.isDigit(fmtSize.charAt(index))) { |
| 1379 |
index++; |
| 1380 |
} |
| 1381 |
|
| 1382 |
|
| 1383 |
if (index == 0 || index == fmtSize.length()) { |
| 1384 |
return Long.MIN_VALUE; |
| 1385 |
} |
| 1386 |
|
| 1387 |
long value = sign * Long.valueOf(fmtSize.substring(0, index)); |
| 1388 |
String unit = fmtSize.substring(index).trim(); |
| 1389 |
|
| 1390 |
return toBytes(value, unit); |
| 1391 |
} |
| 1392 |
|
| 1393 |
|
| 1394 |
|
| 1395 |
|
| 1396 |
|
| 1397 |
|
| 1398 |
|
| 1399 |
|
| 1400 |
|
| 1401 |
|
| 1402 |
@Deprecated |
| 1403 |
public static void closeQuietly(@Nullable AutoCloseable closeable) { |
| 1404 |
IoUtils.closeQuietly(closeable); |
| 1405 |
} |
| 1406 |
|
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
|
| 1412 |
|
| 1413 |
|
| 1414 |
|
| 1415 |
|
| 1416 |
@Deprecated |
| 1417 |
public static void closeQuietly(@Nullable FileDescriptor fd) { |
| 1418 |
IoUtils.closeQuietly(fd); |
| 1419 |
} |
| 1420 |
|
| 1421 |
|
| 1422 |
public static int translateModeStringToPosix(String mode) { |
| 1423 |
|
| 1424 |
for (int i = 0; i < mode.length(); i++) { |
| 1425 |
switch (mode.charAt(i)) { |
| 1426 |
case 'r': |
| 1427 |
case 'w': |
| 1428 |
case 't': |
| 1429 |
case 'a': |
| 1430 |
break; |
| 1431 |
default: |
| 1432 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1433 |
} |
| 1434 |
} |
| 1435 |
|
| 1436 |
int res = 0; |
| 1437 |
if (mode.startsWith("rw")) { |
| 1438 |
res = O_RDWR | O_CREAT; |
| 1439 |
} else if (mode.startsWith("w")) { |
| 1440 |
res = O_WRONLY | O_CREAT; |
| 1441 |
} else if (mode.startsWith("r")) { |
| 1442 |
res = O_RDONLY; |
| 1443 |
} else { |
| 1444 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1445 |
} |
| 1446 |
if (mode.indexOf('t') != -1) { |
| 1447 |
res |= O_TRUNC; |
| 1448 |
} |
| 1449 |
if (mode.indexOf('a') != -1) { |
| 1450 |
res |= O_APPEND; |
| 1451 |
} |
| 1452 |
return res; |
| 1453 |
} |
| 1454 |
|
| 1455 |
|
| 1456 |
public static String translateModePosixToString(int mode) { |
| 1457 |
String res = ""; |
| 1458 |
if ((mode & O_ACCMODE) == O_RDWR) { |
| 1459 |
res = "rw"; |
| 1460 |
} else if ((mode & O_ACCMODE) == O_WRONLY) { |
| 1461 |
res = "w"; |
| 1462 |
} else if ((mode & O_ACCMODE) == O_RDONLY) { |
| 1463 |
res = "r"; |
| 1464 |
} else { |
| 1465 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1466 |
} |
| 1467 |
if ((mode & O_TRUNC) == O_TRUNC) { |
| 1468 |
res += "t"; |
| 1469 |
} |
| 1470 |
if ((mode & O_APPEND) == O_APPEND) { |
| 1471 |
res += "a"; |
| 1472 |
} |
| 1473 |
return res; |
| 1474 |
} |
| 1475 |
|
| 1476 |
|
| 1477 |
public static int translateModePosixToPfd(int mode) { |
| 1478 |
int res = 0; |
| 1479 |
if ((mode & O_ACCMODE) == O_RDWR) { |
| 1480 |
res = MODE_READ_WRITE; |
| 1481 |
} else if ((mode & O_ACCMODE) == O_WRONLY) { |
| 1482 |
res = MODE_WRITE_ONLY; |
| 1483 |
} else if ((mode & O_ACCMODE) == O_RDONLY) { |
| 1484 |
res = MODE_READ_ONLY; |
| 1485 |
} else { |
| 1486 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1487 |
} |
| 1488 |
if ((mode & O_CREAT) == O_CREAT) { |
| 1489 |
res |= MODE_CREATE; |
| 1490 |
} |
| 1491 |
if ((mode & O_TRUNC) == O_TRUNC) { |
| 1492 |
res |= MODE_TRUNCATE; |
| 1493 |
} |
| 1494 |
if ((mode & O_APPEND) == O_APPEND) { |
| 1495 |
res |= MODE_APPEND; |
| 1496 |
} |
| 1497 |
return res; |
| 1498 |
} |
| 1499 |
|
| 1500 |
|
| 1501 |
public static int translateModePfdToPosix(int mode) { |
| 1502 |
int res = 0; |
| 1503 |
if ((mode & MODE_READ_WRITE) == MODE_READ_WRITE) { |
| 1504 |
res = O_RDWR; |
| 1505 |
} else if ((mode & MODE_WRITE_ONLY) == MODE_WRITE_ONLY) { |
| 1506 |
res = O_WRONLY; |
| 1507 |
} else if ((mode & MODE_READ_ONLY) == MODE_READ_ONLY) { |
| 1508 |
res = O_RDONLY; |
| 1509 |
} else { |
| 1510 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1511 |
} |
| 1512 |
if ((mode & MODE_CREATE) == MODE_CREATE) { |
| 1513 |
res |= O_CREAT; |
| 1514 |
} |
| 1515 |
if ((mode & MODE_TRUNCATE) == MODE_TRUNCATE) { |
| 1516 |
res |= O_TRUNC; |
| 1517 |
} |
| 1518 |
if ((mode & MODE_APPEND) == MODE_APPEND) { |
| 1519 |
res |= O_APPEND; |
| 1520 |
} |
| 1521 |
return res; |
| 1522 |
} |
| 1523 |
|
| 1524 |
|
| 1525 |
public static int translateModeAccessToPosix(int mode) { |
| 1526 |
if (mode == F_OK) { |
| 1527 |
|
| 1528 |
|
| 1529 |
return O_RDONLY; |
| 1530 |
} else if ((mode & (R_OK | W_OK)) == (R_OK | W_OK)) { |
| 1531 |
return O_RDWR; |
| 1532 |
} else if ((mode & R_OK) == R_OK) { |
| 1533 |
return O_RDONLY; |
| 1534 |
} else if ((mode & W_OK) == W_OK) { |
| 1535 |
return O_WRONLY; |
| 1536 |
} else { |
| 1537 |
throw new IllegalArgumentException("Bad mode: " + mode); |
| 1538 |
} |
| 1539 |
} |
| 1540 |
|
| 1541 |
|
| 1542 |
@VisibleForTesting |
| 1543 |
public static ParcelFileDescriptor convertToModernFd(FileDescriptor fd) { |
| 1544 |
Context context = AppGlobals.getInitialApplication(); |
| 1545 |
if (UserHandle.getAppId(Process.myUid()) == getMediaProviderAppId(context)) { |
| 1546 |
|
| 1547 |
|
| 1548 |
return null; |
| 1549 |
} |
| 1550 |
|
| 1551 |
try (ParcelFileDescriptor dupFd = ParcelFileDescriptor.dup(fd)) { |
| 1552 |
return MediaStore.getOriginalMediaFormatFileDescriptor(context, dupFd); |
| 1553 |
} catch (Exception e) { |
| 1554 |
|
| 1555 |
return null; |
| 1556 |
} |
| 1557 |
} |
| 1558 |
|
| 1559 |
private static int getMediaProviderAppId(Context context) { |
| 1560 |
if (sMediaProviderAppId != -1) { |
| 1561 |
return sMediaProviderAppId; |
| 1562 |
} |
| 1563 |
|
| 1564 |
PackageManager pm = context.getPackageManager(); |
| 1565 |
ProviderInfo provider = context.getPackageManager().resolveContentProvider( |
| 1566 |
MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE |
| 1567 |
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE |
| 1568 |
| PackageManager.MATCH_SYSTEM_ONLY); |
| 1569 |
if (provider == null) { |
| 1570 |
return -1; |
| 1571 |
} |
| 1572 |
|
| 1573 |
sMediaProviderAppId = UserHandle.getAppId(provider.applicationInfo.uid); |
| 1574 |
return sMediaProviderAppId; |
| 1575 |
} |
| 1576 |
|
| 1577 |
|
| 1578 |
@VisibleForTesting |
| 1579 |
public static class MemoryPipe extends Thread implements AutoCloseable { |
| 1580 |
private final FileDescriptor[] pipe; |
| 1581 |
private final byte[] data; |
| 1582 |
private final boolean sink; |
| 1583 |
|
| 1584 |
private MemoryPipe(byte[] data, boolean sink) throws IOException { |
| 1585 |
try { |
| 1586 |
this.pipe = Os.pipe(); |
| 1587 |
} catch (ErrnoException e) { |
| 1588 |
throw e.rethrowAsIOException(); |
| 1589 |
} |
| 1590 |
this.data = data; |
| 1591 |
this.sink = sink; |
| 1592 |
} |
| 1593 |
|
| 1594 |
private MemoryPipe startInternal() { |
| 1595 |
super.start(); |
| 1596 |
return this; |
| 1597 |
} |
| 1598 |
|
| 1599 |
public static MemoryPipe createSource(byte[] data) throws IOException { |
| 1600 |
return new MemoryPipe(data, false).startInternal(); |
| 1601 |
} |
| 1602 |
|
| 1603 |
public static MemoryPipe createSink(byte[] data) throws IOException { |
| 1604 |
return new MemoryPipe(data, true).startInternal(); |
| 1605 |
} |
| 1606 |
|
| 1607 |
public FileDescriptor getFD() { |
| 1608 |
return sink ? pipe[1] : pipe[0]; |
| 1609 |
} |
| 1610 |
|
| 1611 |
public FileDescriptor getInternalFD() { |
| 1612 |
return sink ? pipe[0] : pipe[1]; |
| 1613 |
} |
| 1614 |
|
| 1615 |
@Override |
| 1616 |
public void run() { |
| 1617 |
final FileDescriptor fd = getInternalFD(); |
| 1618 |
try { |
| 1619 |
int i = 0; |
| 1620 |
while (i < data.length) { |
| 1621 |
if (sink) { |
| 1622 |
i += Os.read(fd, data, i, data.length - i); |
| 1623 |
} else { |
| 1624 |
i += Os.write(fd, data, i, data.length - i); |
| 1625 |
} |
| 1626 |
} |
| 1627 |
} catch (IOException | ErrnoException e) { |
| 1628 |
|
| 1629 |
} finally { |
| 1630 |
if (sink) { |
| 1631 |
SystemClock.sleep(TimeUnit.SECONDS.toMillis(1)); |
| 1632 |
} |
| 1633 |
IoUtils.closeQuietly(fd); |
| 1634 |
} |
| 1635 |
} |
| 1636 |
|
| 1637 |
@Override |
| 1638 |
public void close() throws Exception { |
| 1639 |
IoUtils.closeQuietly(getFD()); |
| 1640 |
} |
| 1641 |
} |
| 1642 |
} |