Sunday, April 27, 2008

Read and Write Files in Java

Here is a sample code I just wrote. This class copies one file to another.
By understanding this code below , you will comphrend both reading from and writing to file concepts in java. I used FileInputStream and FileOutputStream in this code.

package javacream;

import java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.IOException;

public class FileUtil {

public static void copyFile(String strInputFileName , String strOutputFileName) throws IOException {

//Prepare file objects

File fInputFile = new File(strInputFileName);

File fOutputFile = new File(strOutputFileName);

//Prepare read write streams from file objects

FileInputStream fis = new FileInputStream(fInputFile);

FileOutputStream fos = new FileOutputStream(fOutputFile);

int c;

// read from the input file and write to the output file

while ((c = fis.read()) != -1) {

fos.write(c);

}

//we are done , close the streams.

fis.close();

fos.close();

}

public static void main(String[] args) {

try {

// use \\ for windows filenames , otherwise use single /

copyFile("d:\\sample.txt", "d:\\copyof_sample.txt");

} catch (IOException e) {

e.printStackTrace();

}

}

}




Alternatively , you can use FileReader object and BufferedReader. The sample code below counts the number of lines of a given file.

public static int lineCount(String fileName) throws IOException{

// file reader to read the file

FileReader input = new FileReader(fileName);

// Filter FileReader through a BufferedReader to read line by line

BufferedReader bufRead = new BufferedReader(input);

String line; // String that holds current file line

int count = 0; // Line count

// Read first line

line = bufRead.readLine();

count++;

// Read through file one line at time.

while (line != null){

line = bufRead.readLine();

count++;

}

bufRead.close();

return count;

}

Tuesday, April 22, 2008

Java HTTP GET POST

As you know HTTP (Hypertext Transfer Protocol) is the transport protocol of www. Java has a strong support for HTTP.

HTTP addresses uses addressing syntax called URL (for example http://www.java.com). HTTP is based on TCP.

HTTP GET

This is the most widespred type of HTTP request. If you write http://www.java.com/ on your browser you have already made an HTTP GET Request. Here is a sample :

public static String doGET(String strURL) throws IOException {

String response = null;

InputStream in = null;

try {

// setup url connection

URL url = new URL(strURL);

HttpURLConnection urlConn = (HttpURLConnection) url

.openConnection();

in = urlConn.getInputStream();

StringBuilder sb = new StringBuilder();

int i;

while ((i = in.read()) > -1)

sb.append((char) i);

response = sb.toString();

} finally {

if (in != null)

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

To run:
String getResult = doGET("http://javacream.blogspot.com/2008/04/java-http-get-post.html");
System.out.println(getResult);

HTTP POST

When you fill a form on your browser and submit it , most probably you did an HTTP Post to remote server. HTML forms uses POST method alot. In POST method , instead of adding parameters at the and of the url , you post in your request body. So , URL and Parameters are seperate. Check out this sample code for HTPP Post :

public static String doPost(String _url, String line)

throws IOException {

String response = null; //for reading from remote host

InputStream in = null; //for posting parameters to remote host

DataOutputStream out = null;

try {

// setup url connection. use POST to send forms data

URL url = new URL(_url);

HttpURLConnection urlConn = (HttpURLConnection) url

.openConnection();

urlConn.setRequestMethod("POST");

urlConn.setDoInput(true);

urlConn.setDoOutput(true);

urlConn.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded");

out = new DataOutputStream(urlConn.getOutputStream());

out.writeBytes(line);

out.flush();

in = urlConn.getInputStream();

StringBuilder sb = new StringBuilder();

int i;

while ((i = in.read()) > -1)

sb.append((char) i);

response = sb.toString();

} finally {

if (in != null)

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

if (out != null)

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

To run:
String result = doPost("http://www.someserver.com/cgi-bin/form", "userid=Test&Password=Test");

Download a file using HTTP GET

This is a very simple sample code for downloading a file :

public static void downloadFile(String _url, String fileName)

throws IOException {

FileOutputStream outFile = null;

outFile = new FileOutputStream(fileName);

InputStream in = null;

try {

// setup url connection.

URL url = new URL(_url);

HttpURLConnection urlConn = (HttpURLConnection) url

.openConnection();

urlConn.setUseCaches(false);

in = urlConn.getInputStream();

int i = -1;

while ((i = in.read()) > -1)

outFile.write(i);

} finally {

if (in != null)

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

if (outFile != null)

try {

outFile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}


Using with proxies

You have to define proxy before you open connection to your URL.

Properties sysProps = System.getProperties();
sysProps.put("http.proxyHost","proxy.local.intranet") ;
sysProps.put("http.proxyPort", "8080") ;

URL url = new URL(_url);

HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

If the proxy requires Authentication than the following java example code should be added:

sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String basicAuthenticationUserPass =
encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes());
urlConn.setRequestProperty
("Proxy-Authorization", "Basic " + basicAuthenticationUserPass );

Thursday, April 17, 2008

Arrays in Java

Arrays in java are objects that hold fixed numbers of values of single type. Length of the array must be given at initalization , arrays cannot grow or shrink. Each element has an index value starting from 0 , so if you want to reach element 3 , index is 2..



Simple array initializations :

// array of integer with the capacity of 2 integers
int[] intArray = new int[2];

or ,

// [] goes to intArray which makes intArray[]
int intArray[] = new int[2];


Element indexes start from 0(zero) , so the last element index of array above is 1,

intArray[0] = 1;
intArray[1] = 2;


there is no intArray[2] because there is no third element. Capacity is 2.

System.out.println("the length of
intArray="+intArray.length());

gives : the length of intArray=2

You can initialize our sample intArray easily like that :

int intArray[] = new int[]{1,2};

The length of the array will be the same with number of elements you specified.

You can also use Array classes' fill() method like this

Array.fill(intArray,10);

which fills the array with the specified value.


Arrays can hold not only primitive types as stated above, but also objects.

Arrays can also be multidimensional :

int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} };

or with String objects

String[][] friends = {{"Mr. ", "Mrs. ", "Ms. "},
{"Brown", "Parker"}};
//3x2 Array of Strings
System.out.println(
friends[0][0] + friends[1][0]); //Mr. Brown
System.out.println(
friends[0][2] + friends[1][1]); //Ms. Parker

Note that if you don't put elements in an array of objects all elements are null.

String[] strArray = new String[2];
strArray[0] = "first string";
if ( strArray[1] == null )
System.out.println("Second string is null");

gives the output Second string is null when launched

To copy an array into another use
System.arraycopy() method.

String[] strArray1 = new String[]{"banana","apple"};
String[] strArray2 = new String[2];

//copy array strtArray1 into strArray2
//starting from element 0 in strArray1 and start copy

//to strArray2[0] with 2 elements
System.arraycopy(strArray1, 0 , strArray2, 0, 2);
System.out.println(Arrays.toString(strArray2));

gives the output
[banana, apple]

You can also sort the array above using Arrays.sort() method

Arrays.sort(strArray1);
System.out.println(Arrays.toString(strArray1));

gives the output
[apple, banana]

Note that elements of the array should be either primitive or implement Comperable interface to use Arrays.sort()

You can assign one element to another. But note that primitive types and immutable objects are assigned to value , while mutable objects are assigned to reference (just in the case of method call). Confused ? Look at the following sample code. int and String gets the only value of other element but mutable java.util.Date objects gets the reference of the other element and completely becomes the other element. (be to spoon and bend yourself) :

int[] intArray = new int[]{1,2}; //array of primitive
intArray[0] = intArray[1];
intArray[1] = 1000;
System.out.println("intArray[0]="+intArray[0]); //prints 2 not 1000

String[] strArray = new String[]{"string1","string2"};//array of immutable objects
strArray[0] = strArray[1];
strArray[1] = "Mr. Hide";
//print string2 no mrhide!
System.out.println("strArray[0]="+strArray[0]);

java.util.Date[] dateArray = new
java.util.Date[2];//array of mutable objects
long tenMinutesAgo = System.currentTimeMillis() - 10 * 60 * 1000 ;
dateArray[0] = new Date();
dateArray[1] = new Date(tenMinutesAgo);
//prints the current date
System.out.println("dateArray[0]"+dateArray[0].toString());
dateArray[0] = dateArray[1];
//prints 10 minutes ago
System.out.println("dateArray[0]"+dateArray[0].toString());
long twelfMinutesAgo = tenMinutesAgo - 10 * 60 * 1000 ;
dateArray[1].setTime(twelfMinutesAgo);
//prints 20 minutes ago date1 equals date2
System.out.println("dateArray[0]"+dateArray[0].toString());