Posts

Showing posts from April, 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) {

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.

Arrays in Java

Image
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(in