Wednesday, November 5, 2014

STREAM ITEM JAVA PROGRAM



Read file using FileInputStream

import java.io.*;
public class ReadStringFromFile
public static void main(String[] args)
{
File file = new File("C://FileIO//ReadString.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try 
 
 fin = new FileInputStream(file);
while( (ch = fin.read()) != -1)
strContent.append((char)ch);
fin.close();
}
catch(FileNotFoundException e)
{
System.out.println("File " + file.getAbsolutePath() +
" could not be found on filesystem");
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file" + ioe);
}
System.out.println("File contents :");
System.out.println(strContent);
  }
}

Iterate through elements Java Vector using ListIterator

import java.util.Vector;
import java.util.ListIterator; 
public class IterateThroughVectorUsingListIteratorExample
{
public static void main(String[] args)
{
Vector v = new Vector();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
ListIterator itr = v.listIterator();
System.out.println("Iterating through Vector elements in forward direction...");
while(itr.hasNext())
System.out.println(itr.next());
System.out.println("Iterating through Vector elements in backward direction...");
while(itr.hasPrevious())
System.out.println(itr.previous());
  }
}

Remove All Items From a List

import java.applet.Applet;
import java.awt.List;
public class RemoveAllItemsFromAList extends Applet
{
public void init()
{
List list = new List(5, true);
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
list.add("Six");
list.add("Seven");
add(list);
list.removeAll();
  }
}

Swap elements of Java ArrayList

import java.util.ArrayList;
import java.util.Collections;
public class SwapElementsOfArrayListExample
{
 public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("Before swaping, ArrayList contains : " arrayList);
Collections.swap(arrayList,0,4);
System.out.println("After swaping, ArrayList contains : " + arrayList);
   }
}

No comments:

Post a Comment