001/******************************************************************************* 002 * Copyright (C) 2009-2011 FuseSource Corp. 003 * Copyright (c) 2004, 2008 IBM Corporation and others. 004 * 005 * All rights reserved. This program and the accompanying materials 006 * are made available under the terms of the Eclipse Public License v1.0 007 * which accompanies this distribution, and is available at 008 * http://www.eclipse.org/legal/epl-v10.html 009 * 010 *******************************************************************************/ 011package org.fusesource.hawtjni.generator.util; 012 013import java.io.BufferedInputStream; 014import java.io.ByteArrayInputStream; 015import java.io.File; 016import java.io.FileInputStream; 017import java.io.FileNotFoundException; 018import java.io.FileOutputStream; 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022 023/** 024 * 025 * @author <a href="http://hiramchirino.com">Hiram Chirino</a> 026 */ 027public class FileSupport { 028 029 public static boolean write(byte[] bytes, File file) throws IOException { 030 if( !equals(bytes, file) ) { 031 FileOutputStream out = new FileOutputStream(file); 032 try { 033 out.write(bytes); 034 } finally { 035 out.close(); 036 } 037 return true; 038 } 039 return false; 040 } 041 042 public static void copy(InputStream is, OutputStream os) throws IOException { 043 try { 044 byte data[] = new byte[1024*4]; 045 int count; 046 while( (count=is.read(data, 0, data.length))>=0 ) { 047 os.write(data, 0, count); 048 } 049 } finally { 050 close(is); 051 close(os); 052 } 053 } 054 055 public static boolean equals(byte[] bytes, File file) throws IOException { 056 FileInputStream is = null; 057 try { 058 is = new FileInputStream(file); 059 return equals(new ByteArrayInputStream(bytes), new BufferedInputStream(is)); 060 } catch (FileNotFoundException e) { 061 return false; 062 } finally { 063 close(is); 064 } 065 } 066 067 public static void close(InputStream is) { 068 try { 069 if (is != null) 070 is.close(); 071 } catch (Throwable e) { 072 } 073 } 074 075 public static void close(OutputStream ioss) { 076 try { 077 if (ioss != null) 078 ioss.close(); 079 } catch (Throwable e) { 080 } 081 } 082 083 public static boolean equals(InputStream is1, InputStream is2) throws IOException { 084 while (true) { 085 int c1 = is1.read(); 086 int c2 = is2.read(); 087 if (c1 != c2) 088 return false; 089 if (c1 == -1) 090 break; 091 } 092 return true; 093 } 094 095 096 097}