001    /**
002     * 
003     */
004    package de.jw.cloud42.webapp.utils;
005    
006    import java.io.File;
007    import java.io.FileInputStream;
008    import java.io.IOException;
009    import java.io.InputStream;
010    
011    /**
012     * Contains some convenience functions for handling file data.
013     * 
014     * @author fbitzer
015     *
016     */
017    public class FileUtils {
018            
019            /**
020             * Returns the contents of the file in a byte array.
021             * Source: http://www.exampledepot.com/egs/java.io/File2ByteArray.html
022             * @param file
023             * @return
024             * @throws IOException
025             */
026        public static byte[] getBytesFromFile(File file) throws IOException {
027            InputStream is = new FileInputStream(file);
028        
029            // Get the size of the file
030            long length = file.length();
031        
032            // You cannot create an array using a long type.
033            // It needs to be an int type.
034            // Before converting to an int type, check
035            // to ensure that file is not larger than Integer.MAX_VALUE.
036            if (length > Integer.MAX_VALUE) {
037                // File is too large
038            }
039        
040            // Create the byte array to hold the data
041            byte[] bytes = new byte[(int)length];
042        
043            // Read in the bytes
044            int offset = 0;
045            int numRead = 0;
046            while (offset < bytes.length
047                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
048                offset += numRead;
049            }
050        
051            // Ensure all the bytes have been read in
052            if (offset < bytes.length) {
053                throw new IOException("Could not completely read file "+file.getName());
054            }
055        
056            // Close the input stream and return bytes
057            is.close();
058            return bytes;
059        }
060    
061            
062        public static String extractFilename(String path){
063            
064            
065                    
066            File f = new File(path);
067            return f.getName();
068            
069            
070            
071        }
072    
073    }