Saturday, November 1, 2014

Java File Pro



Flush output stream

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FlushStream
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//WriteByte.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
String strContent = "This example shows how to flush output stream!";
dos.writeBytes(strContent);
dos.flush();
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
      }
    }
}

Write String as bytes to a file using Data Output Stream

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteStringAsBytesToFile
 {
public static void main(String[] args)
{
String strFilePath = "C://FileIO//WriteStringAsBytes.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
String str = "This string will be written to file as sequence of bytes!";
dos.writeBytes(str);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
    }
  }
}

Write boolean to a file using Data Output Stream

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteBooleanToFile
 {
public static void main(String[] args)
{
 String strFilePath = "C://FileIO//WriteBoolean.txt";
 try
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
    
boolean b = false;
dos.writeBoolean(b);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
     }
   }
}

Write byte to a file using Data Output Stream

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteByteToFile
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//WriteByte.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
int i = 1;
dos.writeByte(i);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
     }
   }
}

Write char to a file using Data Output Stream

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteCharToFile
{
 public static void main(String[] args)
{
String strFilePath = "C://FileIO//WriteChar.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
int ch = 65;
dos.writeChar(ch);
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
     }
   }
}

No comments:

Post a Comment