content: /*
   * Copyright 2024 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     https://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package com.google.unity.plugin;
  
  import android.os.Environment;
  import android.util.Log;
  
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.nio.file.Files;
  
  public class FileHandler {
      public static boolean copyStreamToFile(InputStream is, File outFile) throws IOException {
          if (is == null || outFile == null) {
              if (UnityDebugHelper.logEnabled)
                  Log.e(UnityDebugHelper.Tag, "Failed to write file");
              return false;
          }
  
          File tmpOutputFile = new File(outFile.getPath() + ".tmp");
          try (OutputStream os = Files.newOutputStream(tmpOutputFile.toPath())) {
              copyStream(is, os);
          }
          if (!tmpOutputFile.renameTo(outFile)) {
              throw new IOException();
          }
          return true;
      }
  
      public static void copyStream(InputStream inputStream, OutputStream outputStream)
              throws IOException {
          byte[] buffer = new byte[8192];
          int amountRead;
          while ((amountRead = inputStream.read(buffer)) != -1) {
              outputStream.write(buffer, 0, amountRead);
          }
      }
  
      public static boolean isExternalStorageAvailable() {
          String extStorageState = Environment.getExternalStorageState();
          return Environment.MEDIA_MOUNTED.equals(extStorageState);
      }
  }
  