Thursday, May 2, 2013

Java / Inner classes


Inner classes.
There are two types of inner classes:
- static (static nested classes)
- non-static (inner classes)

Non-static nested classes have access to other members of the enclosing class,
even if they are declared private.
Static nested classes don't have access to other members of the enclosing class.

There are few reasons for using nested classes.
- logical grouping classes used in one place
- increasing encapsulation
- more readable and maintainable code

public class MyNested 
{
 private int x = 10;
 private int y = 15;
 
 public void showAddition()
 {
  Operation o = new Operation();  
  System.out.println( o.add() );
 }
 
 class Operation
 {
  private int add()
  {
   System.out.println( "Adding" );
   return x+y;
  }
 }
 
 // ! 
 // Static nested classes don't have access to members of enclosing classes 
 static class StaticOperation
 {
  private int add()
  {
   return x+y;
  }
 }
 
 public static void main(String[] args) 
 {
  MyNested n = new MyNested();
  n.showAddition();
  
  // To instantiate an inner class, you must first instantiate the outer class. 
  // Then, create the inner object within the outer object 
  MyNested.Operation op = n.new Operation();
  op.add();

 }
}

Java / Initialization of variables


How can we initialize fields?
There are few ways to do it.

1. Initialization in its declaration - but sometimes we need some logic to do that.
2. Initialization in static block
3. Initialization in block
4. Initialization in constructor
5. Initialization by method


public class MyInitialization 
{
 static int a, b;
 int x, y;
 String name;
 String address;
 
 
 // 1. initialization in its declaration 
 int age = 30;
 
 // 2. initialization in static block 
 static
 {
  a = 7;
  b = 9;  
 }
 
 // 3. initialization in block 
 {
  x = 21;
  y = 23;  
 }
 
 // 4. initialization in constructor 
 MyInitialization()
 {
  this.name = "John";
 }
 
 // 5. initialization by method 
 public void setAddress(String aAddress)
 {
  this.address = aAddress;
 }
 
 public void setX(int aX)
 {
  this.x = aX;
 }

 public static void main(String[] args) 
 {  
  MyInitialization mt = new MyInitialization();
  
  System.out.println( mt.age );  // 1
  
  System.out.println( MyInitialization.a ); // 2
  System.out.println( MyInitialization.b ); // 2
  
  System.out.println( mt.x ); // 3
  System.out.println( mt.y ); // 3
  
  System.out.println( mt.name ); // 4
    
  mt.setAddress("London"); // 5
  System.out.println( mt.address );
 }
}

Java / Enum type


Enum type is a data type that enables for a variable to be a set of predefined constants.
The variable must be equal to one of the values that have been predefined for it.
Because they are constants, the names of an enum type's fields are in uppercase letters.
enum WeekDays 
{
 MONDAY, THUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class MyEnum
{
 WeekDays weekDays;
 
 public MyEnum(WeekDays aWeekDays) 
 {
  this.weekDays = aWeekDays;
 }
 
 public void showCommentForEachDay()
 {
  if( weekDays.equals(WeekDays.SATURDAY) || weekDays.equals(WeekDays.SUNDAY) )
   System.out.println("I like weekends");
  else
   System.out.println("Waiting for weekend... it's " + this.weekDays);
 }
 
 public static void main(String[] args)
 {
  MyEnum me = new MyEnum(WeekDays.SATURDAY);
  me.showCommentForEachDay(); /* out: I like weekends */
 }
}

Sunday, April 28, 2013

Java / break and continue statements


Difference between break and continue statement.
- break - loop is terminated
- continue - stops the normal flow of loop and returns to the loop without executing statement after the continue statement.


public class MyBreak 
{
 public static void main(String[] args) 
 {
  for(int i=0; i<30; i++)
  {
   System.out.print(i);
   
   if(i == 10)
   {
    System.out.println(" \nBreaking the loop when i == 10 ");
    break;    
   }
   System.out.println(" NEXT...");
  }
  System.out.println("End of first loop\n");
  
  for(int i=0; i<30; i++)
  {
   System.out.print(i);
   
   if(i == 10)
   {
    System.out.println(" \nContinue statement when i == 10");
    continue;    
   }
   System.out.println(" and still iterating...");
  }
 }
}


As you can see break statement terminated loop when i == 10.
Continue statement only terminated flow when i == 10 and returned to the iteration.

Wednesday, April 3, 2013

Java - references and passing object to the method


In below example you can see how object is passed to the method.

Objects in Java are passed by reference (or value of the reference). Objects are stored on the heap.

Primitive types in Java are passed by value and they are stored on the stack.

package p_2013_04_03;

class Dog
{
 public String name;
 
 public Dog( String aName )
 {
  this.name = aName;
 }
 
 public void getName()
 {
  System.out.println(this.name);
 }
 
 public void setName( String aName )
 {
  this.name = aName;
 }
}

public class Reference 
{ 
 
 public static void main(String[] args) 
 {
  Dog myDog = new Dog("Raff");
  myDog.getName();
  
  Reference ref = new Reference();
  ref.foo(myDog); // changing name for "Rex" in foo method 
  
  // "myDog" have got new name = "Rex". NOT "Max"
  myDog.getName();
 }
 
 // object is passed by reference (value of reference is passed to function)
 public void foo( Dog aSomeDog )
 {
  // reference to "myDog"
  aSomeDog.getName();
  aSomeDog.setName("Rex");
  
  // assigning new reference to object "aSomeDog" (NOT "myDog"!!!)
  aSomeDog = new Dog("Max");
  aSomeDog.getName();
 }
}

As you can see reference to "myDog" named Raff was passed to the foo method.
Now we have got two references to the "myDog" object.
Then we changed named from Raff to Rex.

After that we have assign new object to the given reference and we have changed name to Max - but name of "myDog" wasn't changed because that reference doesn't point longer at the "myDog" object.

Java / serialize and deserialize object

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment. From Wikipedia


In our example we have got class Person which is implementing Serializable interface. It is needed for serialization our Person class.

In line #42 we are starting serialization and writing serialized data to the file.

In line #64 we are starting reading data from file and then data is deserialized.

It is very simple.

package p_2013_04_03;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


class Person implements java.io.Serializable
{
 private static final long serialVersionUID = 1L;
 
 private String name;
 private int age;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}


public class MySerialization 
{

 public static void main(String[] args) 
 {
  Person john = new Person();
  john.setName("John");
  john.setAge(30);       
  
  // serialize and write serialized data to the file
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
     
  try 
  {
   fos = new FileOutputStream("person.txt");
   oos = new ObjectOutputStream(fos);
   
   oos.writeObject(john);
   fos.close();
   oos.close();
  } 
  catch (FileNotFoundException e) 
  {  
   e.printStackTrace();
  } 
  catch (IOException e) 
  { 
   e.printStackTrace();
  }
  
  // Read serialized data from the file and deserialize 
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  Person desPersonJohn = new Person();   
  
  try 
  {
   fis = new FileInputStream("person.txt");
   ois = new ObjectInputStream(fis);
      
   desPersonJohn = (Person)ois.readObject();
  } 
  catch (FileNotFoundException e) 
  {  
   e.printStackTrace();
  } 
  catch (IOException e) 
  {  
   e.printStackTrace();
  } 
  catch (ClassNotFoundException e) 
  {  
   e.printStackTrace();
  }
  
  System.out.println(desPersonJohn.getName() + " " + desPersonJohn.getAge());  
 }
}

Java - for and for each loop

Below you can see example of looping over an array.
First loop is done using "for each" statement.
Second loop is done using "for" statement.
package p_2013_04_03;

public class MyLoop 
{
 //Examples of iterating through an arrays
 public static void main(String[] args) 
 {  
  int[] myTable = {1,2,4,7,44,56,44};  
 
  // for each loop in java 
  for( int x : myTable )
  {
   System.out.println( x );
  }
  
  // Another way of iterating through an array 
  for(int i=0; i < myTable.length; i++)
  {
   System.out.println( myTable[i] );
  }
 }
}

Java - HashMap example and iterating through HashMap

Here is example of HashMap.

Now we will put some objects to the HashMap.
First we will create new Car class.
After that you can see how to add some object to these collection in line #39.
In line #46 we are checking if there is key "two" in our HashMap.
In line #49 we are checking if there is value "four" in HashMap.
In line #52 we are checking how much keys there is in our HashMap.
In line #54 you can see how get Object from HashMap by key.
In line #59 we are removing Object by key.

In lines #62 and #68 there is iterating through HashMap by key and
in line #74 there is iterating by value.

package p_2013_04_03;

import java.util.HashMap;
import java.util.Map;

class Car
{
 private String brand;
 private int year;
 
 public Car( String aBrand, int aYear )
 {
  this.brand = aBrand;
  this.year = aYear;
 }
 
 public void showBrand()
 {
  System.out.println( this.brand );
 }
 
 public void showYear()
 {
  System.out.println( this.year );
 }
}

public class MyHashMap 
{
 public static void main(String[] args) 
 {
  HashMap hm = new HashMap();
  
  Car opel = new Car("Opel", 2009);
  Car ford = new Car("Ford", 2007);
  Car bmw = new Car("BMW", 2011);
  Car mercedes = new Car("Mercedes", 2011);
  
  // put new value to the Map
  hm.put("one", opel);
  hm.put("two", ford);
  hm.put("three", bmw);
  hm.put("four", mercedes);
  
  // check if Map contains key: true or false
  System.out.println( hm.containsKey("two") );
  
  // check if Map contains value: true or false
  System.out.println( hm.containsKey("four") );
  
  // return the number of keys
  System.out.println( hm.size() );  
  
  // get object from the Map by key 
  Car carFromThree = hm.get("three");
  carFromThree.showBrand();
  
  // remove object from Map
  hm.remove("three");  
  
  // Iterate through Map - by key
  for(Map.Entry entry : hm.entrySet())
  {
   System.out.println( "Key: " + entry.getKey() + " | Value : " + entry.getValue() );
  }
  
  // Iterate through Map - by key
  for(String key : hm.keySet())
  {
   System.out.println( "Key: " + key );
  }
  
  // Iterate through Map - by value
  for(Car car : hm.values())
  {
   System.out.print( "Value: " );
   car.showBrand();
  }
 }
}

Java final field, method and class.

Here is some short example of:
- final field
- final method
- final class


package p_2013_04_03;

public class MyFinalExamples 
{
 // final field is defined and cannot be reassign 
 private final String myFinalString = "I am final string";
 
 // Final field cannot be assigned and if you inherit class you can't override final method 
 public final void setMyFinalString( String aFinalString )
 {
  this.myFinalString = aFinalString;
 }  
}

final class MyFinalExamples02 extends MyFinalExamples
{
 // Final methods can not be overridden 
 public void setUserName( String aUserName )
 {
  this.userName = aUserName;  
 }
}

// Misconception - can't subclass the final subclasses 
class MyFinalExamples03 extends MyFinalExamples02
{
 
}



Example of final field:
In line #9 we are trying to redefine the final field - but you can't do that.

Example of final method:
In line #9 there is final method that can't be overridden when that class will be inherited. So we are trying to override that method in line #18 in inherited class - that is not possible.

Example of final class:
In line #15 we have got final class which is inherited by class in line #25. It can't be done because final class cannot be inherited.

Sunday, March 31, 2013

jQuery / $.post - How to send data with jQuery to other file

How to send data to other file with jQuery post() method?

Sometimes we want to send data without refreshing page.
Solution is simple. Using jQuery post() method we can send different types of  data (variables, arrays, forms, serialized data, etc.) and after that we can for example write these data to the database.

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery post method</title>

<script type="text/javascript">
$(document).ready(function()
{
    $('#J_action_sendPersonSalary').click( function()
 {
  var personId = 34;
  var personSalary = 2000;
  
  $.post( "person.php", {personId: personId, personSalary: personSalary} ); 
 });
});
</script>
 
</head>
<body>

 <a id="J_action_sendPersonSalary" href="javascript:void(0)">Send data with salary</a>
    
</body>
</html>

person.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<?php

 $personId = $_POST['personId'];
 $personSalary = $_POST['personSalary'];
 
 // Here we can do something with our data. For example send it to the database.
 $query = 'INSERT INTO ....';

?>

</body>
</html>

Sunday, March 24, 2013

Java / immutable objects - example: String object

What are immutable objects?
Immutable object are objects whose state cannot be changed.

Example of immutable object (String):

public class MyImmutable 
{
 public static void main(String[] args) 
 {
  String myString = new String( "my string" );
  
  myString.replace("my", "my new");
  System.out.println("Original String (immutable): " + myString);
  
  String newMyString = myString.replace("my", "my new");
  System.out.println("New String: " + newMyString);  
 }
}
Java official immutable tutorial

Java / Scanner class. Simple example of Sanner.in

How to read something from console?
Java provides Scanner class to read from input.

Example:

import java.util.Scanner;

public class MyScanner 
{
 public static void main(String[] args) 
 {
  Scanner in = new Scanner( System.in );
  boolean isExit = false;
  
  while( !isExit )
  {
   System.out.println( "Write something to me" );
   String line = in.nextLine();
   
   System.out.println( "Your text: " + line );
   
   if( line.equals("exit") )
   {
    isExit = true;
    System.out.println( "You have choosen exit. Bye bye." );
   }
  }
  in.close();
 }
}


In this loop you can read everything you want from console and your text will be displayed in line #15..
If you type "exit" the program will terminate.

More about Scanner class you can read from official documentation here. (Java 1.6)

Tuesday, March 19, 2013

jQuery / JSON / get some date from other file

How to retrieve some information from other page using JSON?

Example of how to use JSON.

1. index.php

<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_getData").click( function()        
        {
            $.post("fileWithData.php", { "getData": "cars" }, function(data)
            {
                var obj = jQuery.parseJSON(data);
                $("#mymsg").html( obj[0] + " " + obj[1] ); 
            });            
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_getData" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">
        
    </div>

</body>
</html>

2. fileWithData.php

<html>
<head>
<title>j</title>

</head>

<body> 
<?php
    if($_POST['getData'] == "cars")
    {
        $cars = array();
        $cars[1] = "Mercedes";
        $cars[2] = "Audi";
        echo json_encode($cars);
    }        
?>
</body>
</html>

Some details about parse JSON here.
Details of encoding and decoding JSON in PHP here.

jQuery / adding CSS style dynamically

How to add some css styles dynamically with jQuery?
jQuery comes with css() function to do that.

Example shows how to change dynamically text color.

<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_addCssStyle").click( function()
        {
            $("#mymsg").css("color", "red");
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_addCssStyle" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">
        This is my text.
    </div>

</body>
</html>

Official documentation of jQuery css is here.

jQuery / dynamic removing CSS class

How to remove some css class dynamically with jQuery?
jQuery comes with removeClass() function to do that.

Example of dynamically removing css class.

<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<style type="text/css">
    .backgroundGreen{
        background-color: #00ff00;
    }
 </style>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_removeCssClass").click( function()
        {
            $("#mymsg").removeClass("backgroundGreen");
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_removeCssClass" href="javascript:void(0)" >Show message</a>

    <div id="mymsg" class="backgroundGreen">
        This is my text.
    </div>

</body>
</html>

Official documentation of jQuery removeClass is here.

jQuery / dynamic adding CSS class


How to add some css class dynamically with jQuery?
jQuery comes with addClass() function to do that.

Example of dynamically adding css class.
<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<style type="text/css">
    .redFont{ 
        color: #FF0000;
    }
 </style>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_addCssClass").click( function()
        {
            $("#mymsg").addClass("redFont");
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_addCssClass" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">
        This is my text.
    </div>

</body>
</html>

Official documentation is here.

jQuery library from Google - online

How to use jQuery library from Google?
It is free to use and you can use it on your page if it is connected to the web.

Just put below code to your www page between <head></head> tags.

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>

</body>
</html>

Search for a new libraries here.

jQuery click() function.

jQuery click()
Simple Hello World display on mouse click.

When "Show message" link is clicked it calls jQuery click() function.

Example of jQuery click() function

<html>
<head>
<title>jQuery</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#J_action_showMessage").click( function()
        {
            $("#mymsg").html("Hello World");
        });        
    });
 
</script>

</head>

<body> 
    
    <a id="J_action_showMessage" href="javascript:void(0)" >Show message</a>

    <div id="mymsg">

    </div>

</body>
</html>

Official documentation of jQuery click() function here.

Tuesday, March 12, 2013

LEFT JOIN in database

How to join at least two tables from database?

First create tables:

1. Table with cars:
CREATE TABLE `cars` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `make` varchar(50) DEFAULT NULL,
  `model` varchar(50) DEFAULT NULL,
  `year` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Table with users:
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `cars_id` int(10) DEFAULT NULL,
  `name` varchar(40) DEFAULT NULL,
  `surname` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Now insert some rows with data to our tables.

There is foreign key - cars_id - in table users.
We will use foreign key to join cars with users.

INSERT INTO
        cars
        (
            make,
            model,
            year
        )
    VALUES
        (
            "Opel",
            "Vectra",
            "2012-05-25"
        );

INSERT INTO
        users
        (
            cars_id,
            name,
            surname
        )
    VALUES
        (
            1,
            "John",
            "Smith"
        );
And now you can join our tables:
SELECT
  *
FROM
  cars
LEFT JOIN users ON users.cars_id = cars.id

How to DELETE data from database


Deleting data from database is easy.

If you have a table with data from previous example (here is example) you can try our next code:


DELETE
    FROM
        cars
    WHERE
        id = 3;

If you don't have row with id = 3 just chane it to other number.
That is all.

How to UPDATE data in database

How to update data in database system?

Try it using previous example from here because we need table with data.

To update data in database (MySQL, PostgreSQ etc.) use below code:


UPDATE cars
    SET        
        model = "Vectra 2"
    WHERE
        id = 3;
Remember that you need to have row with id = 3 in your database.
Otherwise just change "id" to other number in the above example.

How to SELECT data from database - MySQL example

How to select data from mysql?

Short example in MySQL.

First: create new table in MySQL.


CREATE TABLE `cars` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `make` varchar(50) DEFAULT NULL,
  `model` varchar(50) DEFAULT NULL,
  `year` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

After that insert few rows of data to the table.
Below is example how to do it.
INSERT INTO
        cars
        (
            make,
            model,
            year
        )
    VALUES
        (
            "Opel",
            "Vectra",
            "2012-05-25"
        );
Now we can retrive data from MySQL:

SELECT
    id,
    make
FROM
    cars;
or (not good - because slower)
SELECT
    *
FROM
    cars;

Monday, March 11, 2013

Load content to jQuery dialog on open

How to load content to jQuery dialog on open from other file?

It is very easy.

Just use my code on your page. Put code between <body></body> tags.

1. First create new file: index.html




Open my dialog



2. Create second file: cars.html
  • Audi
  • Ford
  • Honda
  • Toyota
That is all. Now you can load content from other file when jQuery dialog is opening.

Styling jQuery dialog


Dialog is like it is.
But if we want to make it better we can restyle dialog a little ;)

Few things to restylish jQuery dialog. Looks better in each browser (IE 9+) .

1. Put my code into <body> </body> tags on your page and play with jQuery dialog styling it.



Open my dialog


jQuery dialog

Dialog is a window where we can put some hidden details on our page and make it visible on user requests.
How to create and use jQuery dialog?

1. You need jQuery library included between <head> </head> tags.
You can download it from official site.
ex.:

<head><script src="http://code.jquery.com/jquery-1.9.1.min.js"></script></head>


2. Put my code between <body> </body> tags.


Open my dialog


That is all. Have fun!

Redirect page with JavaScript - jQuery

How to redirect page with jQuery?
Create first file and paste code between <body></body> tags.

1. File name: index.html



Redirect my page to second file
My first page: index.html
Now create second file and paste code between <body> </body>  tags.

2. File name: secondFile.html


Redirect my page to index
My second page: secondFile.html
Redirecting page with jQuery is easy and fast to do.

jQuery / Refresh page


1. jQuery. How to refresh page with JavaScript using jQuery?

Paste code between <body></body> tags.
Now you can refresh page. That's all;)

If you dont believe me( ;) ) that page was reloaded just click on "Insert new text" link and you will see that text have changed in "placeToInsertText" div.
Now click "Refresh my page" link and page will be refreshed.



Refresh my page
Insert new text
My text number 1.

Java / Write to file

How to write text to file?
Construct a FileWriter object associated with a file descriptor.
Create a buffered character-output stream that uses a default-sized output buffer.
Write a String to file.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile 
{
 public static void main(String[] args) 
 {
  File file = new File( "readme.txt" );  
  try 
  {
   FileWriter fw = new FileWriter( file );
   BufferedWriter bw = new BufferedWriter( fw );
   bw.write( "New text to write to file" );
   
   bw.close();
   
   System.out.println( "Writing ended successfuly" );
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  }
 }
}


Java / Read from file

How to read from a file?
There are few ways to read from file in Java. I will show you one of the most common used method.
Create file descriptor - use File class to do this.
Create new FileReader.
Create new BufferedReader.
Read line by line.

1. Create file "readme.txt" in your project workspace and add few lines.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFile 
{
 public static void main(String[] args) 
 {
  String line = null;
  File file = new File( "readme.txt" );
  
  FileReader fr = null;
  try 
  {
   fr = new FileReader( file );
  } 
  catch (FileNotFoundException e) 
  {  
   System.out.println( "File doesn't exists" );
   e.printStackTrace();
  }
  BufferedReader br = new BufferedReader( fr );
  
  try 
  {
   while( (line = br.readLine()) != null )
   {
    System.out.println( line );
   }
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  }
 }
}


Java / Create new directory

How to create new directory?
Use File class and mkdir() method.
This method returns true if directory was created otherwise false


import java.io.File;

public class MakeDir 
{
 public static void main(String[] args) 
 {
  File file = new File( "ReadmeTest" );
  boolean result = file.mkdir();
  
  if( result == true )
   System.out.println( "Directory was created" );
  else
   System.out.println( "Directory wasn't created or already exists" );
 }
}

Java / Check if is directory

How to check if given file name is directory?
Use File class and isDirectory() method.
This method returns true if directory exists otherwise false

import java.io.File;

public class IsDirecory 
{
 public static void main(String[] args) 
 {
  File file = new File("readme.txt");
  boolean result = file.isDirectory();
  
  if( result == true )
   System.out.println( "It is a direcory" );
  else
   System.out.println( "Directory doesn't exists or isn't a directory" );
 }
}

Java / Check if file is file or not

How to check if file is a file or not?
Use File class and isFile() method.
This method returns true if file is a file otherwise false


import java.io.File;

public class IsFile 
{
 public static void main(String[] args) 
 {
  File file = new File("readme.txt");
  boolean result = file.isFile();
  
  if( result == true )
   System.out.println( "It is a file" );
  else
   System.out.println( "File doesn't exists or isn't a file" );
 }
}

Java / Check if file or directory exists



How to check if file exists?
Use File class and exists() method
If file or directory exists it will return true otherwise false


import java.io.File;

public class ExistsFile 
{
 public static void main(String[] args) 
 {
  File file = new File("readme.txt");
  boolean result = file.exists();
  
  if( result == true )
   System.out.println( "File exists" );
  else
   System.out.println( "File doesn't exists" );
 }
}

Java / Delete file, directory


How to delete file or direcory in Java?
Use File class and delete() method.
This method deletes file or directory if exists and returning true on success otherwise false.

import java.io.File;

public class DeleteFile 
{
 public static void main(String[] args) 
 {
  File file = new File( "readme.txt" );
  boolean result = file.delete();
  
  if( result == true )
   System.out.println( "File deleted" );
  else
   System.out.println( "File doesn't exists" );
 }
}

Java / Create new file


How to create new file in Java?
This method creates file only if file doesn't exists.
We have to use File class and createNewFile() method.
File will be created in your workspace -> project directory.

import java.io.File;
import java.io.IOException;

public class CreateFile 
{
 public static void main(String[] args) 
 {
  File file = new File( "readme.txt" );
  
  try 
  {
   boolean result = file.createNewFile();
   
   if( result == true )
    System.out.println( "File created" );
   else
    System.out.println( "File already exists" );
  } 
  catch (IOException e) 
  {   
   e.printStackTrace();
  }
 }
}

Sunday, March 10, 2013

My first jQuery script


If you downloaded jQuery library (official site) you can start wiriting your first script.

Create new index.html page and paste code between <body> </body> tag.
When page ends loading html code jQuery will start. First you will see JavaScript alert with "This is my first jQuery code" message and after that "Hello World" text will be inserted into "myText" div.


 

Is it simple?
Remember to put jQuery (JavaScript) code in document.ready function because jQuery code have to be started after DOM loads end.

What is jQuery?

"Query is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers."
 In addition, a great advantage is that a jQuery is small library.

Now you can write JavaScript code faster. To do it just download library from official site and put path to library between<head></head> tag.




    Exaple of jQuery use
    




Java - JDBC. Connect to database.

The Java Database Connectivity (JDBC) allows you to connect to the database.
Below are examples of how to connect to the database ( MySQL and PostgreSQL) using JDBC.

Quick link:

Connect to MySQL via JDBC connector

Connect to MySQL and PostgreSQL via JDBC connector

Friday, March 8, 2013

Simple connecting to MySQL with PHP

How to connect to MySQL in PHP?
It's simple.
$username = "root";
$password = "password";
$host = "localhost"; 

$dbhandle = mysql_connect($host, $username, $password) 
     or die("Unable to connect to MySQL");
echo "Connected to MySQL";

$selected = mysql_select_db("dbName", $dbhandle) 
    or die("There is no database");

$result = mysql_query("SELECT model FROM cars");

while($row = mysql_fetch_array($result)) 
{
    echo "MODEL: ".$row['model'];
}

mysql_close($dbhandle);

That is all. Simple?

Newer and better way to connect:
$db = new PDO( 'mysql:host=localhost; dbname=MyDbName; charset=utf8', 'username', 'password' );

$statement = $db -> query('SELECT model FROM cars');
foreach($statement as $row)
{
    echo $row['model'];
}

jQuery load(). Dynamic load content without refreshing page


How to upload file content from other file using jQuery load() function without refreshing page?
You can do it using only AJAX or shortcut from jQuery.

Downlod jQuery file from here and put in index.html file within<head> </head> or paste path to jQuery file in internet.



When you click "Get cars" link it calls function load().

1. File index.html - our main file


Get cars

    Place to load data from other file...
2. File cars.html - from this file content will be loaded.
  • Opel
  • Ford
  • BMW
  • Mercedes

Java / Connect to MySQL


How connect to MySQL database using JDBC MySQL connector?
Download MySQL connector

Add connector to your Java project. It is simple - just click right mouse button on project and choose "Build Path" --> "Configure Build Path" --> "Java Build Path" and add connector *.jar library.

1. Here is simple, short example how to register and connect do MySQL via JDBC connector:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBexample 
{   
 public static void main(String[] args) throws SQLException 
 {
  Connection conn = null;
  
  try 
  {   
   Class.forName("com.mysql.jdbc.Driver"); 
   
   try 
   {
    conn = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "password");
   } 
   catch (SQLException e) 
   {
    System.out.println("Check DB link / user / password");
    e.printStackTrace();
   }
  }
  catch(ClassNotFoundException e) 
  {
   System.out.println("There is no connector");
   System.out.println(e.getMessage());
   System.exit(-1);
  }
  
  System.out.println("Connector registered");
  
  conn.close();
 }
}
That's all!

Thursday, March 7, 2013

Connect to MySQL, PostgreSQL using JDBC

Now I will show you how to connect to MySQL and PostgreSQL database using JDBC connector.
We need connector.
Download MySQL connector.
Download PostgreSQL connector.

In Eclipse:
Right click on your Java project -> Buil Path -> Configure Build Path -> Java Build Path and add your jar

1. Short example (for MySQL):


Connection con = null;
Statement stmt;
ResultSet rs;

Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
con = DriverManager.getConnection( "jdbc:mysql://hostname:port/dbname","username", "password" );
stmt = con.createStatement();

con.close();
stmt.close();
rs.close();

2. Full example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBexample
{
 String dbLogin, dbPswd, dbUrl;
 
 Connection con = null;
 Statement stmt;
 ResultSet rs;
 
 /* There are two database systems:
  * - mysql
  * - pg */
 public DBexample( String databaseSystem )
 {
  if( databaseSystem.equals( "mysql" ) )
  {
   this.dbLogin = "root";
   this.dbPswd = "password";
   this.dbUrl = "jdbc:mysql://localhost:3306/dbname";
   
   try
   {
    Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
    con = DriverManager.getConnection( this.dbUrl, this.dbLogin, this.dbPswd );
    stmt = con.createStatement();
   }
   catch (Exception e) 
   {
    System.out.println( "There is no connector available." );
    return;
   }  
   
   System.out.println( "Connector registered" );
   
  }
  else if( databaseSystem.equals( "pg" ) )
  {
   this.dbLogin = "root";
   this.dbPswd = "password";
   this.dbUrl = "jdbc:postgresql://localhost:5432/dbname";
   
   try
   {
    Class.forName( "org.postgresql.Driver" );
    con = DriverManager.getConnection( this.dbUrl, this.dbLogin, this.dbPswd );
    stmt = con.createStatement();
   }
   catch (Exception e)
   {
    System.out.println( "There is no connector available." );
    return;
   }
   
   System.out.println( "Connector registered" );
  }  
 }
 
 /* Execute sql: update, insert, delete... */
 public void executeUpdate(String aQuery) throws SQLException
 {
  stmt.executeUpdate(aQuery);
 }
 
 /* Execute sql: select... and get result */
 public ResultSet executeSelect( String aQuery )
 {
  try 
  {
   rs = stmt.executeQuery(aQuery);
  } 
  catch (SQLException e) 
  {  
   e.printStackTrace();
  }    
  return rs;
 }
 
 public void closeConnection() throws SQLException
 {
  con.close();
  stmt.close();
  rs.close();
 }
 
 /* Test */
 public static void main(String[] argv) throws SQLException 
 {
  ResultSet rs;
  
  /* Connect to MySQL and get all cars */
  DBexample dbMySQL = new DBexample("mysql");
  rs = dbMySQL.executeSelect("SELECT * FROM cars");  
  
  try 
  {
   while( rs.next() )
   {
    String carModel = rs.getString( "model" );
    System.out.println( carModel );   
   }
  } 
  catch (SQLException e) 
  {  
   e.printStackTrace();
  }
  /* close connection */
  dbMySQL.closeConnection();
  
  /* *********************************************************************** */
  
  /* Connect to PostgreSQL and get all users */
  DBexample dbPg = new DBexample("pg");
  rs = dbPg.executeSelect("SELECT * FROM users");
  
  try 
  {
   while( rs.next() )
   {
    String userName = rs.getString( "userName" );
    System.out.println( userName );   
   }
  } 
  catch (SQLException e) 
  {  
   e.printStackTrace();
  }
  /* close connection */
  dbPg.closeConnection();
 }
}




blogorama.com