Monday, November 7, 2011

close file handler in java while operating on files

I just bumped into one of the error with file io. if you dont close fie handler, it wont write anything into file.
import java.io.*;
class FileWrite 
{
 public static void main(String args[])
  {
  try{
  // Create file 
  FileWriter fstream = new FileWriter("out.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write("Hello Java");
  //Close the output stream
  out.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

executing external process using java

Runtime rt=Runtime.getRuntime();
  Process x= rt.exec("ls -l");
  BufferedReader stdInput = new BufferedReader(new 
                InputStreamReader(x.getInputStream()));
  String s;
  while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

Adding new elements to arraylist in java while using iterator

today i had a problem with usage of arraylist along side of iterator. the problem was that i was unable to add elements to the arraylist. it gives you an error java.util.ConcurrentModificationException this is because u cant add elements to an arraylist while using an iterator. so i had used listiterator as below.

import java.util.ArrayList;
import java.util.ListIterator;
public class Test 
{
 public static void main(String args[])
 {
  ArrayList array_test= new ArrayList();
  array_test.add("a");
  array_test.add("k");
  array_test.add("d");
  array_test.add("s");
  array_test.remove("d");
  int i=1;
  for(ListIterator it=array_test.listIterator();it.hasNext();)
  { 
   String link=it.next(); 
   if(i==1)
   {  
    it.add("r");
    it.previous();
    it.add("kk");
    it.previous();
   i++;
   }
   System.out.println(link);
   
  } 
   
  System.out.println("Contents of arrays list "+array_test);
 }
 

}

In the above code i had used it.previous whenever i used it.add. this is because i want to use the added value in the loop again. while the addition of new element in array is added just before next element in arraylist.