Some Useful Java Stuff - pwc21@yahoo.com


Returns an estimate of the size (as it would exist in memory or on disk) of the object you pass it. Object must be serializable. Use with caution on large objects.
    public static int getObjectSize(Serializable obj)
    {
        ObjectOutputStream oos = null;
        
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
        
            oos.writeObject(obj);
            oos.flush();
            
            return baos.size();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return -1;
        }
        finally
        {
            try { oos.close(); } catch(Exception e) {}
        }
    }
    

Attempts to return the name of the current method.
    /**
     * Prints the name of the method that called this method to stdout
     * 
     * @return String the name of the method that called this method.
     */
    public static void printCurrentMethodName()
    {
        System.out.println(getCurrentMethodName(3));
    }
    
    /**
     * Gets the name of the method that called this method to stdout
     * 
     * @return String the name of the method that called this method.
     */
    public static String getCurrentMethodName()
    {
        return getCurrentMethodName(3);
    }
    
    /**
     * Prints the name of the method that called this method to stdout
     * 
     * @param numLinesToIgnore number of lines in the stack trace to ignore
     * @return String the name of the method that called this method.
     */
    public static String getCurrentMethodName(int numLinesToIgnore)
    {
        // Exceptions are an easy way to get call stack information.
        // This method takes advantage of that.
        Throwable t = new Throwable();
        
        // Print the stack trace to a byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        t.printStackTrace(new PrintWriter(baos, true));
        byte[] stackTraceBytes = baos.toByteArray();
        
        String line = null;
        
        // Now read from that byte array, line by line
        try
        {
            ByteArrayInputStream bais = new ByteArrayInputStream(stackTraceBytes);
            BufferedReader in = new BufferedReader(new InputStreamReader(bais));
            
            // We need to skip the first couple of lines of the stack trace, because we only
            // want the line that pertains to our calling method.
            in.readLine();  // always ignore the first lines
            for (int i = 0; i < numLinesToIgnore - 1; i++)
            {
                in.readLine();  // clear lines that we don't need
            }
            
            line = in.readLine();
            in.close();
        }
        catch (IOException e)
        {
            // nothing to do
        }
        
        // The stack trace line begins with "at ", so trim it off to give us a clean method name
        String methodName = line.substring(4, line.length());
        
        return methodName;
    }
    

Returns true if the current operating system is Windows.
    public static boolean systemIsWindows()
    {
        if(File.separatorChar == '\\')
           return true;
        return false;
    }
    

Changes an exception stack trace into a string.
    public static String getStackTraceAsString(Throwable e)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(bytes, true);
        e.printStackTrace(writer);
        String str = bytes.toString();

        try
        {
            writer.close();
            bytes.close();
        }
        catch(IOException ex) { }

        return str;
    }
    

Search and replace for substrings inside a string.
    public static String replaceSubstring(String orig, String searchFor, String replaceWith)
    {
        int index = orig.indexOf(searchFor);
        if(index < 0)
            return orig;
            
        StringBuffer sb = new StringBuffer();
        sb.append(orig.substring(0, index));
        sb.append(replaceWith);
        sb.append(orig.substring((index+searchFor.length())));
        return sb.toString();
    }

    public static String replaceSubstringAll(String orig, String searchFor, String replaceWith)
    {
        int index = 0;
        StringBuffer sb = new StringBuffer(orig);
        while((index = sb.toString().indexOf(searchFor, index)) != -1)
        {
            sb.replace(index, index+searchFor.length(), replaceWith);
            index += replaceWith.length();
        }
        return sb.toString();
    }
    

Convenience utility methods for reading and writing files using strings and bytes.
    public static void writeContentsFromString(String contents, File f) throws IOException
    {
        FileOutputStream fos = new FileOutputStream(f);
        PrintWriter out = new PrintWriter(fos);

        out.print(contents);
        out.flush();

        out.close();
        fos.close();
    }

    public static String readContentsToString(File f) throws IOException, FileNotFoundException
    {
        FileInputStream fis = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(fis);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        
        byte[] buffer = new byte[bis.available()];
        
        bis.read(buffer);
        bos.write(buffer);
        
        String contents = bos.toString();
        
        bos.close();
        
        bis.close();
        fis.close();

        return contents;
    }
    
    public static byte[] readContentsToBytes(File f) throws FileNotFoundException, IOException
    {
        FileInputStream fis = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(fis);
        
        byte[] buffer = new byte[bis.available()];
        bis.read(buffer);

        bis.close();
        fis.close();
        
        return buffer;
    }
    
    public static void writeContentsFromBytes(File f, byte[] contents, boolean overwrite) throws IOException
    {
        if(!f.exists() || (f.exists() && overwrite))
        {
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            
            bos.write(contents);

            bos.close();
            fos.close();
        }
    }
    

Executes any operating system command or program, returns the results as a string.
    public static String execute(String command) throws IOException
    {
        Process process = Runtime.getRuntime().exec(command);
        InputStream is = process.getInputStream();
        String s = new String(getStreamAsBytes(is));
        is.close();
        return s;
    }
    

Convenience method to construct a new object using reflection, given the class name.
    public static Object constructNew(String className, Object arg) throws InstantiationException 
    {
        try
        {
            if(arg == null)
                return Class.forName(className).newInstance();
            
            Class c = Class.forName(className);
            Class[] contructorArgs = {arg.getClass()};
            Constructor constructor = c.getConstructor(contructorArgs);
            Object[] args = {arg};
            return constructor.newInstance(args);
        }
        catch(Exception e)
        {
            throw new InstantiationException("Problem constructing new " + className + ". Exception is " + e);
        }
    }
    


http://www.buzzsurf.com