Home | History | Annotate | Download | only in vault
      1 /*
      2  * Copyright (C) 2013 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.example.android.vault;
     18 
     19 import android.os.ParcelFileDescriptor;
     20 
     21 import java.io.ByteArrayOutputStream;
     22 import java.io.Closeable;
     23 import java.io.File;
     24 import java.io.FileInputStream;
     25 import java.io.FileOutputStream;
     26 import java.io.IOException;
     27 import java.io.InputStream;
     28 import java.io.OutputStream;
     29 
     30 public class Utils {
     31     public static void closeQuietly(Closeable closable) {
     32         if (closable != null) {
     33             try {
     34                 closable.close();
     35             } catch (IOException ignored) {
     36             }
     37         }
     38     }
     39 
     40     public static void closeWithErrorQuietly(ParcelFileDescriptor pfd, String msg) {
     41         if (pfd != null) {
     42             try {
     43                 pfd.closeWithError(msg);
     44             } catch (IOException ignored) {
     45             }
     46         }
     47     }
     48 
     49     public static void writeFully(File file, byte[] data) throws IOException {
     50         final OutputStream out = new FileOutputStream(file);
     51         try {
     52             out.write(data);
     53         } finally {
     54             out.close();
     55         }
     56     }
     57 
     58     public static byte[] readFully(File file) throws IOException {
     59         final InputStream in = new FileInputStream(file);
     60         try {
     61             ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     62             byte[] buffer = new byte[1024];
     63             int count;
     64             while ((count = in.read(buffer)) != -1) {
     65                 bytes.write(buffer, 0, count);
     66             }
     67             return bytes.toByteArray();
     68         } finally {
     69             in.close();
     70         }
     71     }
     72 }
     73