1/* 2 * Copyright (C) 2015 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 17package android.support.provider.tests; 18 19import android.content.Context; 20import android.os.ParcelFileDescriptor; 21 22import java.io.File; 23import java.io.FileOutputStream; 24import java.io.IOException; 25import java.io.InputStream; 26 27/** 28 * Utilities for tests. 29 */ 30final class TestUtils { 31 /** 32 * Saves a file from resources to a temporary location and returns a File instance for it. 33 * 34 * @param id Resource ID 35 */ 36 static File createFileFromResource(Context context, int id) throws IOException { 37 final File file = File.createTempFile("android.support.provider.tests{", 38 "}.zip", context.getCacheDir()); 39 try ( 40 final FileOutputStream outputStream = 41 new ParcelFileDescriptor.AutoCloseOutputStream( 42 ParcelFileDescriptor.open( 43 file, ParcelFileDescriptor.MODE_WRITE_ONLY)); 44 final InputStream inputStream = context.getResources().openRawResource(id); 45 ) { 46 final byte[] buffer = new byte[32 * 1024]; 47 int bytes; 48 while ((bytes = inputStream.read(buffer)) != -1) { 49 outputStream.write(buffer, 0, bytes); 50 } 51 outputStream.flush(); 52 return file; 53 } 54 } 55} 56