1/* 2 * Copyright (C) 2011 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 17package libcore.java.io; 18 19import java.io.File; 20import java.io.FileDescriptor; 21import java.io.FileInputStream; 22import java.io.FileNotFoundException; 23import java.io.FileOutputStream; 24import java.io.IOException; 25import junit.framework.TestCase; 26 27public class FileOutputStreamTest extends TestCase { 28 public void testFileDescriptorOwnership() throws Exception { 29 File tmp = File.createTempFile("FileOutputStreamTest", "tmp"); 30 FileOutputStream fos1 = new FileOutputStream(tmp); 31 FileOutputStream fos2 = new FileOutputStream(fos1.getFD()); 32 33 // Close the second FileDescriptor and check we can't use it... 34 fos2.close(); 35 try { 36 fos2.write(1); 37 fail(); 38 } catch (IOException expected) { 39 } 40 try { 41 fos2.write(new byte[1], 0, 1); 42 fail(); 43 } catch (IOException expected) { 44 } 45 // ...but that we can still use the first. 46 fos1.write(1); 47 48 // Close the first FileDescriptor and check we can't use it... 49 fos1.close(); 50 try { 51 fos1.write(1); 52 fail(); 53 } catch (IOException expected) { 54 } 55 try { 56 fos1.write(new byte[1], 0, 1); 57 fail(); 58 } catch (IOException expected) { 59 } 60 } 61 62 public void testClose() throws Exception { 63 FileOutputStream fos = new FileOutputStream(File.createTempFile("FileOutputStreamTest", "tmp")); 64 65 // Closing an already-closed stream is a no-op... 66 fos.close(); 67 fos.close(); 68 // ...as is flushing... 69 fos.flush(); 70 71 // ...but any explicit write is an error. 72 byte[] bytes = "hello".getBytes(); 73 try { 74 fos.write(bytes); 75 fail(); 76 } catch (IOException expected) { 77 } 78 try { 79 fos.write(bytes, 0, 2); 80 fail(); 81 } catch (IOException expected) { 82 } 83 try { 84 fos.write(42); 85 fail(); 86 } catch (IOException expected) { 87 } 88 89 // ...except a 0-byte write. 90 fos.write(new byte[0], 0, 0); 91 } 92} 93