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