1/* 2 * Copyright (C) 2013 DroidDriver committers 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 com.google.android.droiddriver.util; 18 19import android.util.Log; 20 21import com.google.android.droiddriver.exceptions.DroidDriverException; 22 23import java.io.BufferedOutputStream; 24import java.io.File; 25import java.io.FileNotFoundException; 26import java.io.FileOutputStream; 27 28/** 29 * Internal helper methods for manipulating files. 30 */ 31public class FileUtils { 32 /** 33 * Opens file at {@code path} to output. If any directories on {@code path} do 34 * not exist, they will be created. The file will be readable to all. 35 */ 36 public static BufferedOutputStream open(String path) throws FileNotFoundException { 37 File file = getAbsoluteFile(path); 38 39 Logs.log(Log.INFO, "opening file " + file.getAbsolutePath()); 40 BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file)); 41 file.setReadable(true /* readable */, false/* ownerOnly */); 42 return stream; 43 } 44 45 /** 46 * Returns a new file constructed using the absolute path of {@code path}. 47 * Unlike {@link File#getAbsoluteFile()}, default parent is "java.io.tmpdir" 48 * instead of "user.dir". 49 * <p> 50 * If any directories on {@code path} do not exist, they will be created. 51 */ 52 public static File getAbsoluteFile(String path) { 53 File file = new File(path); 54 if (!file.isAbsolute()) { 55 file = new File(System.getProperty("java.io.tmpdir"), path); 56 } 57 mkdirs(file.getParentFile()); 58 return file; 59 } 60 61 private static void mkdirs(File dir) { 62 if (dir == null || dir.exists()) { 63 return; 64 } 65 66 mkdirs(dir.getParentFile()); 67 if (!dir.mkdir()) { 68 throw new DroidDriverException("failed to mkdir " + dir); 69 } 70 dir.setReadable(true /* readable */, false/* ownerOnly */); 71 dir.setExecutable(true /* executable */, false/* ownerOnly */); 72 } 73} 74