1 /* 2 * Copyright 2022 Google LLC 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.google.android.libraries.mobiledatadownload.file.common.internal; 17 18 import com.google.android.libraries.mobiledatadownload.file.common.FileChannelConvertible; 19 import com.google.android.libraries.mobiledatadownload.file.common.FileConvertible; 20 import com.google.android.libraries.mobiledatadownload.file.common.Syncable; 21 import java.io.File; 22 import java.io.FileOutputStream; 23 import java.io.IOException; 24 import java.nio.channels.FileChannel; 25 26 /** A File-based OutputStream that implements all optional Backend behaviors. */ 27 public class BackendOutputStream extends ForwardingOutputStream 28 implements FileConvertible, FileChannelConvertible, Syncable { 29 private final FileOutputStream fileOutputStream; 30 private final File file; 31 createForWrite(File file)32 public static BackendOutputStream createForWrite(File file) throws IOException { 33 return new BackendOutputStream(new FileOutputStream(file), file); 34 } 35 createForAppend(File file)36 public static BackendOutputStream createForAppend(File file) throws IOException { 37 return new BackendOutputStream(new FileOutputStream(file, true /* append */), file); 38 } 39 40 /** NOTE: this constructor is public only in order to allow subclassing. */ BackendOutputStream(FileOutputStream fileOutputStream, File file)41 public BackendOutputStream(FileOutputStream fileOutputStream, File file) { 42 super(fileOutputStream); 43 this.fileOutputStream = fileOutputStream; 44 this.file = file; 45 } 46 47 @Override toFile()48 public File toFile() { 49 return file; 50 } 51 52 @Override toFileChannel()53 public FileChannel toFileChannel() { 54 return fileOutputStream.getChannel(); 55 } 56 57 @Override sync()58 public void sync() throws IOException { 59 fileOutputStream.getFD().sync(); 60 } 61 } 62