1 /*
2  * Copyright (C) 2019 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 com.android.server.wifi.util;
18 
19 import android.system.ErrnoException;
20 import android.system.Os;
21 import android.util.Log;
22 
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.nio.charset.StandardCharsets;
26 
27 /**
28  * Utility methods useful for working with files.
29  *
30  * Note: @hide methods copied from android.os.FileUtils
31  */
32 public final class FileUtils {
33     private static final String TAG = "FileUtils";
34 
35     /**
36      * Change the mode of a file.
37      *
38      * @param path path of the file
39      * @param mode to apply through {@code chmod}
40      * @return 0 on success, otherwise errno.
41      */
chmod(String path, int mode)42     public static int chmod(String path, int mode) {
43         try {
44             Os.chmod(path, mode);
45             return 0;
46         } catch (ErrnoException e) {
47             Log.w(TAG, "Failed to chmod(" + path + ", " + mode + "): ", e);
48             return e.errno;
49         }
50     }
51 
52     /**
53      * Writes the bytes given in {@code content} to the file whose absolute path
54      * is {@code filename}.
55      */
bytesToFile(String filename, byte[] content)56     public static void bytesToFile(String filename, byte[] content) throws IOException {
57         try (FileOutputStream fos = new FileOutputStream(filename)) {
58             fos.write(content);
59         }
60     }
61 
62     /**
63      * Writes string to file. Basically same as "echo -n $string > $filename"
64      *
65      * @param filename
66      * @param string
67      * @throws IOException
68      */
stringToFile(String filename, String string)69     public static void stringToFile(String filename, String string) throws IOException {
70         bytesToFile(filename, string.getBytes(StandardCharsets.UTF_8));
71     }
72 }
73