Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, November 8, 2015

Very simple Java String methods: "Split String" and "Capitalize the First Letter "

// Some common simple Java String methods: "Split String" and "Capitalize the First Letter " 

// Split Strings, just like the String split method, but it removes all white spaces.
// I expect a million other implementation of this, but this does the job as well.
public static String[] splitString(String text, String splitChar){
String [] list = text.split(splitChar);

for (int i=0; i<list.length; i++){
list[i] = list[i].trim();
}
return list;
}

// Capitalize the First Letter of the passed in String s
public static String capitalizeFirstLetter(String s){
String result = null;

if (s != null){
if (s.length() >1)
result = s.substring(0, 1).toUpperCase() + s.substring(1, s.length());
else
result = s.toUpperCase();
}
return result;
}

Sunday, October 25, 2015

Simple Java Serialization

// this is a very simple example of java serialization example
//Serializations: Assume this is my class to be serialized
import java.util.ArrayList;

public class Dish {
private String dishName;
private ArrayList<String> ingredient;

public String getDishName(){
return this.className;
}
public ArrayList<String> getIngredient(){
return this.variableNames;
}
public void setDishName(String dishName){
this.dishName = dishName;
}
public void setIngredient(ArrayList<String> ingredient){
this.ingredient = ingredient;
}
}

// This class will read and write. I reused the one found here which is awesome.
// Thanks Awesome person who did this
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
public class Builder {
    public static void writeXML(Schema f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Schema readXML(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        Schema o = (Schema)decoder.readObject();
        decoder.close();
        return o;
    }
}

// This is a class using both
public class Food {
    public static void main(String[] args) {
        String filename = "/home/...../Dishes.xml";
        String name = "Pizza";
        ArrayList<String>  ingredients= new ArrayList<String>();
        vars.add("dough");
        vars.add("cheese");
        vars.add("sauce");

        Schema s = new Schema();
        s.setDishName(name);
        s.setIngredient(ingredients);

         try { Builder.writeXML(s, filename);  }
            catch (Exception ex){ System.out.println(ex); }
         try {
         Schema s2 = Builder.readXML(filename);
         System.out.println(s2.getDishName());
         System.out.println(s2.getIngredient().toString());
         } catch (Exception ex){ System.out.println(ex); }
    }

}//Food


// Java read from a file and return the string
public static String readFile(String fileName){

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String content = "";

String line = null;
   while ((line = reader.readLine()) != null) {
       content = content + line;
   }
   reader.close();
 
   return content;
 
} catch (IOException x) {
   System.err.format("IOException: %s%n", x);
   return null;
}

}

Tuesday, May 29, 2012

Online Compilers

Two cool online compilers for code snippets:
http://codepad.org and http://ideone.com

I tried this C++ Fibonacci function and the compiler worked:

#include <iostream>
 
int fib(int n)
{
     if ( n == 0 ) return 0;
     if ( n == 1 ) return 1;
 
     return fib(n-1) + fib(n-2);
}
 
int main(){
 printf("Fib Val: %i", fib(7));
 return 0;
}

Tuesday, May 8, 2012

JAVA Write to a file

// Write x to file
public void writeFile(String x, String file){
    try{
        // Create file
        FileWriter fstream = new FileWriter(file);
        // Create Writer
        BufferedWriter out = new BufferedWriter(fstream);
        // Write x to the file        
        out.write(x);
        //Close the output stream
        out.close();
    }catch (Exception e){
        //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

Monday, May 7, 2012

JAVA Date and time formatting

public static String getDateNow(){
  DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return (dateFormat.format(date))+"";
}

Sunday, May 6, 2012

JAVA Manipulate a String using regular expressions

// Example 1, remove all instances of a word with another in a String.
// Example 2, remove all white spaces from a String
public static String manipulateString(String s){
  String result = s;
  
  //1 replace all instances of the word foo with the word bee 
  result = result.replaceAll("(?:foo)", "bee");

  // remove all white space
  result = result.replaceAll("\\s+", "");
   
  return result;
}

JAVA Open a file using the default application editor.

// Example Foo.xls will be opened with Excel
// Make sure to import the class java.awt.Desktop

public static void OpenFile(String filename){
  try{
    // Check if class 'Desktop' is supported on the platform 
    if (Desktop.isDesktopSupported()) {
      Desktop.getDesktop().open(new File(filename));
    }else{
      System.out.println("Class Desktop is unsupported");
    }
  } catch (Exception ex){
    System.out.println("Error opening "+ filename);
  }
}