• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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 libcore.testing.io;
18 
19 import java.io.File;
20 import java.util.Random;
21 
22 public class TestIoUtils {
23     private final static Random random = new Random();
24 
TestIoUtils()25     private TestIoUtils() {}
26 
27     /**
28      * Creates a unique new temporary directory under "java.io.tmpdir".
29      */
createTemporaryDirectory(String prefix)30     public static File createTemporaryDirectory(String prefix) {
31         while (true) {
32             String candidateName = prefix + nextRandomInt();
33             File result = new File(System.getProperty("java.io.tmpdir"), candidateName);
34             if (result.mkdir()) {
35                 return result;
36             }
37         }
38     }
39 
40     /**
41      * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
42      */
closeQuietly(AutoCloseable closeable)43     public static void closeQuietly(AutoCloseable closeable) {
44         if (closeable != null) {
45             try {
46                 closeable.close();
47             } catch (RuntimeException rethrown) {
48                 throw rethrown;
49             } catch (Exception ignored) {
50             }
51         }
52     }
53 
nextRandomInt()54     private synchronized static int nextRandomInt() {
55         return random.nextInt();
56     }
57 }
58