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 and writable to 35 * all. 36 */ 37 public static BufferedOutputStream open(String path) throws FileNotFoundException { 38 File file = getAbsoluteFile(path); 39 40 Logs.log(Log.INFO, "opening file " + file.getAbsolutePath()); 41 BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file)); 42 file.setReadable(true /* readable */, false/* ownerOnly */); 43 file.setWritable(true /* readable */, false/* ownerOnly */); 44 return stream; 45 } 46 47 /** 48 * Returns a new file constructed using the absolute path of {@code path}. 49 * Unlike {@link File#getAbsoluteFile()}, default parent is "java.io.tmpdir" 50 * instead of "user.dir". 51 * <p> 52 * If any directories on {@code path} do not exist, they will be created. 53 */ 54 public static File getAbsoluteFile(String path) { 55 File file = new File(path); 56 if (!file.isAbsolute()) { 57 file = new File(System.getProperty("java.io.tmpdir"), path); 58 } 59 mkdirs(file.getParentFile()); 60 return file; 61 } 62 63 private static void mkdirs(File dir) { 64 if (dir == null || dir.exists()) { 65 return; 66 } 67 68 mkdirs(dir.getParentFile()); 69 if (!dir.mkdir()) { 70 throw new DroidDriverException("failed to mkdir " + dir); 71 } 72 dir.setReadable(true /* readable */, false/* ownerOnly */); 73 dir.setWritable(true /* readable */, false/* ownerOnly */); 74 dir.setExecutable(true /* executable */, false/* ownerOnly */); 75 } 76} 77