1 /* 2 * Copyright (C) 2018 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 package com.android.tradefed.util; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 20 import java.io.File; 21 import java.io.FileWriter; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.nio.file.Paths; 25 26 public class VtsFileUtil extends FileUtil { 27 /** 28 * Replacing characters in a string to make it a valid file name. 29 * 30 * The current method is to replace any non-word character with '_' except '.' and '-'. 31 * 32 * @param filename the potential name of a file to normalize. 33 * Do not use path here as path delimitor will be replaced 34 * @return normalized file name 35 */ normalizeFileName(String filename)36 public static String normalizeFileName(String filename) { 37 return filename.replaceAll("[^\\w.-]", "_"); 38 } 39 40 /** 41 * Save a resource file to a directory. 42 * 43 * TODO(yuexima): This method is to be removed when it becomes available in FileUtil. 44 * 45 * @param resourceStream a {link InputStream} object to the resource to be saved. 46 * @param destDir a {@link File} object of a directory to where the resource file will be saved. 47 * @param targetFileName a {@link String} for the name of the file to be saved to. 48 * @return a {@link File} object of the file saved. 49 * @throws IOException if the file failed to be saved. 50 */ saveResourceFile( InputStream resourceStream, File destDir, String targetFileName)51 public static File saveResourceFile( 52 InputStream resourceStream, File destDir, String targetFileName) throws IOException { 53 FileWriter writer = null; 54 File file = Paths.get(destDir.getAbsolutePath(), targetFileName).toFile(); 55 try { 56 writer = new FileWriter(file); 57 StreamUtil.copyStreamToWriter(resourceStream, writer); 58 return file; 59 } catch (IOException e) { 60 CLog.e("IOException while saving resource %s/%s", destDir, targetFileName); 61 deleteFile(file); 62 throw e; 63 } finally { 64 if (writer != null) { 65 writer.close(); 66 } 67 if (resourceStream != null) { 68 resourceStream.close(); 69 } 70 } 71 } 72 }