Friday, October 31, 2014

Java Using File



Skip n bytes while reading the file using File Input Stream

import java.io.*;
public class SkipBytesReadFile
{
public static void main(String[] args)
{
File file = new File("C://FileIO//ReadString.txt");
   
try
{
FileInputStream fin = new FileInputStream(file);
int ch;
fin.skip(10);
while( (ch = fin.read()) != -1 )
System.out.print((char) ch);
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
    }
  }
}

Add an element to specified index of Java Array List

import java.util.ArrayList;
public class AddElementToSpecifiedIndexArrayListExample
{
public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add(1,"Inserted element"); System.out.println("ArrayList contains...");
for(int index=0; index < arrayList.size(); index++)
System.out.println(arrayList.get(index));
   }
}

Append all elements of other Collection to Java Array List

import java.util.ArrayList;
import java.util.Vector;
public class AppendAllElementsOfOtherCollectionToArrayListExample
{
 public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
Vector v = new Vector();
v.add("4");
v.add("5");
arrayList.addAll(v);
System.out.println("After appending all elements of Vector,
ArrayList contains..");
for(int i=0; i
System.out.println(arrayList.get(i));
  }
}

Copy all elements of Java Array List to an Object Array

import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample
{
public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
Object[] objArray = arrayList.toArray();
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
   }
}

Get Size of Java Array List and loop through elements

import java.util.ArrayList;
public class GetSizeOfArrayListExample
{
public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
int totalElements = arrayList.size();  System.out.println("ArrayList contains...");
for(int index=0; index < totalElements; index++)
System.out.println(arrayList.get(index));
   }
}

No comments:

Post a Comment