1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.benchmark
18 
19 import android.os.Build
20 import android.util.Log
21 import androidx.annotation.RequiresApi
22 import androidx.annotation.RestrictTo
23 import androidx.benchmark.BenchmarkState.Companion.TAG
24 import java.io.File
25 import java.io.IOException
26 import java.nio.file.Files
27 
28 /** Uses Java NIO APIs to move files. */
29 @RestrictTo(RestrictTo.Scope.LIBRARY)
30 @RequiresApi(Build.VERSION_CODES.O)
31 object FileMover {
Filenull32     fun File.moveTo(destination: File, overwrite: Boolean = false) {
33         try {
34             if (overwrite) {
35                 destination.delete()
36             }
37             // Ideally we would have used File.renameTo(...)
38             // On Android we cannot rename across mount points so we are using this API instead.
39             Files.move(this.toPath(), destination.toPath())
40         } catch (exception: IOException) {
41             // Moves can fail when trying to move across mount points. This is especially true
42             // for environments like FTL. In such cases, we fallback to trying to copy the file
43             // instead.
44             Log.w(TAG, "Unable to move $this to $destination. Copying, instead.", exception)
45             copyTo(target = destination, overwrite = overwrite)
46         }
47     }
48 }
49