Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2017 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.android.car.test.utils;
     18 
     19 import android.annotation.Nullable;
     20 import android.os.SystemClock;
     21 
     22 import java.io.BufferedWriter;
     23 import java.io.File;
     24 import java.io.FileWriter;
     25 import java.io.IOException;
     26 import java.nio.file.Files;
     27 import java.nio.file.Path;
     28 
     29 /**
     30  * A utility class that creates a temporary file.
     31  * The file is automatically deleted when calling close().
     32  *
     33  * Example usage:
     34  *
     35  * try (TemporaryFile tf = new TemporaryFile("myTest")) {
     36  *     ...
     37  * } // file gets deleted here
     38  */
     39 public final class TemporaryFile implements AutoCloseable {
     40     private File mFile;
     41 
     42     public TemporaryFile(@Nullable String prefix) throws IOException {
     43         if (prefix == null) {
     44             prefix = TemporaryFile.class.getSimpleName();
     45         }
     46         mFile = File.createTempFile(prefix, String.valueOf(SystemClock.elapsedRealtimeNanos()));
     47     }
     48 
     49     public TemporaryFile(File path) {
     50         mFile = path;
     51     }
     52 
     53     @Override
     54     public void close() throws Exception {
     55         Files.delete(mFile.toPath());
     56     }
     57 
     58     public void write(String s) throws IOException {
     59         BufferedWriter writer = new BufferedWriter(new FileWriter(mFile));
     60         writer.write(s);
     61         writer.close();
     62     }
     63 
     64     public FileWriter newFileWriter() throws IOException {
     65         return new FileWriter(mFile);
     66     }
     67 
     68     public File getFile() {
     69         return mFile;
     70     }
     71 
     72     public Path getPath() { return mFile.toPath(); }
     73 }
     74