------------------------------Main.java-------------------------
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
// Stream is used to perform input and output of 16-bit unicode.
// FileReader use the FileInputStream and FileWriter uses the FileOutputStream.
// FileReader read two byte at a time and FileWriter write two byte at a time.
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int readChar;
while((readChar = in.read()) != -1){
out.write(readChar);
}
System.out.println("\nSuccessfully copied/write the text of input.txt to the output.txt file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
in.close();
out.close();
}
}
}
--------------------------OUTPUT----------------------
Wednesday, September 2, 2015
Byte Streams
-------------------------Main.java------------------
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException
{
// Stream represents the input source and output destination
// InputStream is used to read data from the source and
// OutputStream is used to write data to the destination
// Byte Stream is used to perform input and output of 8-bit byte
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("input.txt");
fileOutputStream = new FileOutputStream("output.txt");
int text ;
while((text = fileInputStream.read()) != -1){
fileOutputStream.write(text);
// Copying the text value of input.txt to output.txt
}
System.out.println("\nSuccessfully copied the text of input.txt to the output.txt file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileInputStream != null){
fileInputStream.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
}
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException
{
// Stream represents the input source and output destination
// InputStream is used to read data from the source and
// OutputStream is used to write data to the destination
// Byte Stream is used to perform input and output of 8-bit byte
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("input.txt");
fileOutputStream = new FileOutputStream("output.txt");
int text ;
while((text = fileInputStream.read()) != -1){
fileOutputStream.write(text);
// Copying the text value of input.txt to output.txt
}
System.out.println("\nSuccessfully copied the text of input.txt to the output.txt file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileInputStream != null){
fileInputStream.close();
}
if(fileOutputStream != null){
fileOutputStream.close();
}
}
}
}
---------------------Output----------------------
Tuesday, June 9, 2015
HttpURLConnection
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class URLCOnnectionDemo
{
public static void main(String[] args)
{
try {
URL url = new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlCon = url.openConnection();
InputStream stream = urlCon.getInputStream();
int i;
while((i = stream.read()) != -1){
System.out.print((char)i);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thread Methods
Thread Methods:
public void start()
public void run()
public final void setName(String name)
public final void setPriority(int priority)
public final void setDaemon(boolean on)
public final void join(long millisec)
public void interrupt()
public final boolean isAlive()
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
Methods with Description
public static void yield()
public static void sleep(long millisec)
public static boolean holdsLock(Object x)
public static Thread currentThread()
public static void dumpStack()
public void start()
public void run()
public final void setName(String name)
public final void setPriority(int priority)
public final void setDaemon(boolean on)
public final void join(long millisec)
public void interrupt()
public final boolean isAlive()
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
Methods with Description
public static void yield()
public static void sleep(long millisec)
public static boolean holdsLock(Object x)
public static Thread currentThread()
public static void dumpStack()
Extending Thread Class
public class MainActivity
{
public static void main(String[] args)
{
ExtendingThreadClass obj = new ExtendingThreadClass("THREAD_A");
obj.run();
ExtendingThreadClass obj2 = new ExtendingThreadClass("THREAD_B");
obj2.run();
}
}
----------------------------------------------
public class ExtendingThreadClass extends Thread{
Thread t ;
String threadName;
public ExtendingThreadClass(String threadName)
{
this.threadName = threadName;
System.out.println("Creating thread obj: "+ threadName);
}
@Override
public void run()
{
super.run();
System.out.println("Running thread: "+ threadName);
try {
for(int i = 4; i > 0 ; i-- ){
System.out.println("thread: "+ threadName +" "+ i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread: "+ threadName + " interrupted.");
e.printStackTrace();
}
System.out.println("Thread: "+ threadName +" is exiting");
}
public void start()
{
System.out.println("Starting: "+ threadName);
if(t == null){
t = new Thread(this, threadName);
t.start();
}
}
}
--------------------------------------------------------
Thread Runnable Interface
public class ThreadWidRunnableInterface implements Runnable{
Thread t ;
String threadName;
public ThreadWidRunnableInterface(String threadName) {
this.threadName = threadName;
System.out.println("Creating thread named : "+ threadName);
}
@Override
public void run() {
System.out.println("Running thread: "+ threadName);
try {
for (int i = 4; i > 0 ; i--) {
System.out.println("Thread "+ threadName + " "+ i);
Thread.sleep(50);
}
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("Thread: "+ threadName+"interrupted");
e.printStackTrace();
}
System.out.println("Thread: "+threadName+"exiting");
}
public void start() {
System.out.println("Starting: "+ threadName);
if( t == null ){
t = new Thread(this, threadName);
t.start();
}
}
}
Monday, June 8, 2015
Date and Time format
package dateTimeDemoPackage;
import java.text.DateFormat;
import java.util.Date;
public class FormatDateAndTime
{
public static void main(String[] args)
{
Date currentDate = new Date();
System.out.println("Current Date: "+ currentDate+"\n");
String dateToString = DateFormat.getInstance().format(currentDate);
System.out.println("getInstance() : "+ dateToString+"\n");
dateToString = DateFormat.getDateInstance().format(currentDate);
System.out.println("getDateInstance(): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance().format(currentDate);
System.out.println("getTimeInstance(): "+dateToString+"\n");
dateToString = DateFormat.getDateTimeInstance().format(currentDate);
System.out.println("getDateTimeInstance(): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.SHORT).format(currentDate);
System.out.println("getTimeInstance(DateFormat.SHORT): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(currentDate);
System.out.println("getTimeInstance(DateFormat.MEDIUM): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.LONG).format(currentDate);
System.out.println("getTimeInstance(DateFormat.LONG): "+dateToString+"\n");
dateToString = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(currentDate);
System.out.println("getDateTimeInstance(Dateformat.LONG , DateFormat.SHORT): \n "+ dateToString);
}
}
import java.text.DateFormat;
import java.util.Date;
public class FormatDateAndTime
{
public static void main(String[] args)
{
Date currentDate = new Date();
System.out.println("Current Date: "+ currentDate+"\n");
String dateToString = DateFormat.getInstance().format(currentDate);
System.out.println("getInstance() : "+ dateToString+"\n");
dateToString = DateFormat.getDateInstance().format(currentDate);
System.out.println("getDateInstance(): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance().format(currentDate);
System.out.println("getTimeInstance(): "+dateToString+"\n");
dateToString = DateFormat.getDateTimeInstance().format(currentDate);
System.out.println("getDateTimeInstance(): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.SHORT).format(currentDate);
System.out.println("getTimeInstance(DateFormat.SHORT): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(currentDate);
System.out.println("getTimeInstance(DateFormat.MEDIUM): "+dateToString+"\n");
dateToString = DateFormat.getTimeInstance(DateFormat.LONG).format(currentDate);
System.out.println("getTimeInstance(DateFormat.LONG): "+dateToString+"\n");
dateToString = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(currentDate);
System.out.println("getDateTimeInstance(Dateformat.LONG , DateFormat.SHORT): \n "+ dateToString);
}
}
Date toString()
package dateTimeDemoPackage;
import java.text.DateFormat;
import java.util.Date;
public class DateToString
{
public static void main(String[] args)
{
Date date = new Date();
System.out.println("Date is: "+ date);
String dateToString = DateFormat.getInstance().format(date);
System.out.println("Data formate using getInstance(): "+ dateToString);
}
}
import java.text.DateFormat;
import java.util.Date;
public class DateToString
{
public static void main(String[] args)
{
Date date = new Date();
System.out.println("Date is: "+ date);
String dateToString = DateFormat.getInstance().format(date);
System.out.println("Data formate using getInstance(): "+ dateToString);
}
}
Date and Time
package dateTimeDemoPackage;
import java.util.Date;
public class TimeDemo
{
public static void main(String[] args)
{
System.out.println("-----FirstWay-------");
Date date = new Date();
System.out.println(date);
System.out.println("\n-----SecondWay-------");
long millis = System.currentTimeMillis();
java.util.Date date2 = new Date(millis);
System.out.println(date2);
System.out.println("\n-----ThirdWay-------");
long millisec = System.currentTimeMillis();
java.sql.Date date3 = new java.sql.Date(millisec);
System.out.println(date3);
System.out.println("\n-----FourthWay-------");
Date date4 = java.util.Calendar.getInstance().getTime();
System.out.println(date4);
}
}
import java.util.Date;
public class TimeDemo
{
public static void main(String[] args)
{
System.out.println("-----FirstWay-------");
Date date = new Date();
System.out.println(date);
System.out.println("\n-----SecondWay-------");
long millis = System.currentTimeMillis();
java.util.Date date2 = new Date(millis);
System.out.println(date2);
System.out.println("\n-----ThirdWay-------");
long millisec = System.currentTimeMillis();
java.sql.Date date3 = new java.sql.Date(millisec);
System.out.println(date3);
System.out.println("\n-----FourthWay-------");
Date date4 = java.util.Calendar.getInstance().getTime();
System.out.println(date4);
}
}
Sunday, June 7, 2015
Monday, June 1, 2015
Directory in Java
Directories in Java:
A directory is a File which can contains a list of other files and directories.
You use File object to create directories, to list down files available in a directory.
Creating Directories:
There are two useful File utility methods, which can be used to create directories:
mkdir( ):
method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that
the directory cannot be created because the entire path does not exist yet.
mkdirs():
method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java,
the path will still resolve correctly.
File Writer
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//This class inherits from the OutputStreamWriter class. The class is used for writing
//streams of characters
//FileWriter(File file)
//FileWriter(File file, boolean append)
//FileWriter(FileDescriptor fd)
//FileWriter(String fileName)
//FileWriter(String fileName, boolean append)
// Methods with Description
// public void write(int c) throws IOException
// Writes a single character.
// public void write(char [] c, int offset, int len)
// Writes a portion of an array of characters starting from offset and with a length of len.
// public void write(String s, int offset, int len)
// Write a portion of a String starting from offset and with a length of len.
public class FileWriterClassDemo {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
file.createNewFile();
FileWriter fWriter = new FileWriter(file);
fWriter.write("Space to write awesomeness");
fWriter.flush();
fWriter.close();
FileReader fReader = new FileReader(file);
char[] a = new char[50];
fReader.read(a);
for (char c : a) {
System.out.print(c);
}
fReader.close();
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//This class inherits from the OutputStreamWriter class. The class is used for writing
//streams of characters
//FileWriter(File file)
//FileWriter(File file, boolean append)
//FileWriter(FileDescriptor fd)
//FileWriter(String fileName)
//FileWriter(String fileName, boolean append)
// Methods with Description
// public void write(int c) throws IOException
// Writes a single character.
// public void write(char [] c, int offset, int len)
// Writes a portion of an array of characters starting from offset and with a length of len.
// public void write(String s, int offset, int len)
// Write a portion of a String starting from offset and with a length of len.
public class FileWriterClassDemo {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
file.createNewFile();
FileWriter fWriter = new FileWriter(file);
fWriter.write("Space to write awesomeness");
fWriter.flush();
fWriter.close();
FileReader fReader = new FileReader(file);
char[] a = new char[50];
fReader.read(a);
for (char c : a) {
System.out.print(c);
}
fReader.close();
}
}
File Reader
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//This class inherits from the InputStreamReader class. FileReader is used for reading
//streams of characters.
//FileReader(File file)
//FileReader(FileDescriptor fd)
//FileReader(String fileName)
//Methods with Description
//public int read() throws IOException
//Reads a single character. Returns an int, which represents the character read.
//public int read(char [] c, int offset, int len)
//Reads characters into an array. Returns the number of characters read.
public class FileReaderClassDemo {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
file.createNewFile();
FileWriter fWriter = new FileWriter(file);
fWriter.write("This is \n the text \n to display");
fWriter.flush();
fWriter.close();
FileReader fReader = new FileReader(file);
char a[] = new char[50];
fReader.read(a);
for (char c : a) {
System.out.print(c);
}
fReader.close();
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//This class inherits from the InputStreamReader class. FileReader is used for reading
//streams of characters.
//FileReader(File file)
//FileReader(FileDescriptor fd)
//FileReader(String fileName)
//Methods with Description
//public int read() throws IOException
//Reads a single character. Returns an int, which represents the character read.
//public int read(char [] c, int offset, int len)
//Reads characters into an array. Returns the number of characters read.
public class FileReaderClassDemo {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
file.createNewFile();
FileWriter fWriter = new FileWriter(file);
fWriter.write("This is \n the text \n to display");
fWriter.flush();
fWriter.close();
FileReader fReader = new FileReader(file);
char a[] = new char[50];
fReader.read(a);
for (char c : a) {
System.out.print(c);
}
fReader.close();
}
}
File Object
import java.io.File;
//in case of text1.txt it is false because i do not make a textt.txt file inside the workspace
//in case of text2.txt it is true because i make a text2.txt file inside the workspace
public class FIleObjectDemo {
public static void main(String[] args) {
File f = null;
String[] fileName = {"test1.txt","test2.txt"};
for (String string : fileName) {
f = new File(string);
boolean bool = f.canExecute(); // true if the file is executable
String a = f.getAbsolutePath(); // find the absolute path
System.out.println(a); // print the absolute path
System.out.println("is Executable: "+ bool + "\n");
}
}
}
--------------------------------------------------------------------------------------------------
// OUTPUT:
// Here first we have to make test2.txt file in the workspace
//in case of text1.txt it is false because i do not make a textt.txt file inside the workspace
//in case of text2.txt it is true because i make a text2.txt file inside the workspace
public class FIleObjectDemo {
public static void main(String[] args) {
File f = null;
String[] fileName = {"test1.txt","test2.txt"};
for (String string : fileName) {
f = new File(string);
boolean bool = f.canExecute(); // true if the file is executable
String a = f.getAbsolutePath(); // find the absolute path
System.out.println(a); // print the absolute path
System.out.println("is Executable: "+ bool + "\n");
}
}
}
--------------------------------------------------------------------------------------------------
// OUTPUT:
// Here first we have to make test2.txt file in the workspace
File Navigation and IO
There are several other classes that we would be going through to get to know
the basics of File Navigation and I/O.
File Class
FileReader Class
FileWriter Class
File Class:
Java File class represents the files and directory pathnames in an abstract manner.
This class is used for creation of files and directories, file searching, file deletion etc.
The File object represents the actual file/directory on the disk.
There are following constructors to create a File object:
File(File parent, String child);
File(String pathname)
File(String parent, String child)
File(URI uri)
METHODS:
public String getName()
public String getParent()
public File getParentFile()
public String getPath()
public boolean isAbsolute()
public String getAbsolutePath()
public boolean canRead()
public boolean canWrite()
public boolean exists()
public boolean isDirectory()
public boolean isFile()
public long lastModified()
public long length()
public boolean createNewFile() throws IOException
public boolean delete()
public void deleteOnExit()
public String[] list()
public String[] list(FilenameFilter filter)
public File[] listFiles()
public File[] listFiles(FileFilter filter)
public boolean mkdir()
public boolean mkdirs()
public boolean renameTo(File dest)
public boolean setLastModified(long time)
public boolean setReadOnly()
public static File createTempFile(String prefix, String suffix, File directory) throws IOException
public static File createTempFile(String prefix, String suffix) throws IOException
public int compareTo(File pathname)
public int compareTo(Object o)
public boolean equals(Object obj)
public String toString()
FileInputNOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class InputStreamNNOutputStream {
public static void main(String[] args) throws IOException {
try {
byte bWrite[] = {1,2,3,4,5,6};
OutputStream os = new FileOutputStream("output.txt");
for (int i = 0; i < bWrite.length; i++) {
os.write(bWrite[i]);
}
os.close();
InputStream is = new FileInputStream("output.txt");
int size = is.available();
for (int j = 0; j < size; j++) {
System.out.print((char)is.read() + " - ");
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------------------------------------------------
// OUTPUT :
//The below code would create file test.txt and would write given numbers in binary format.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class InputStreamNNOutputStream {
public static void main(String[] args) throws IOException {
try {
byte bWrite[] = {1,2,3,4,5,6};
OutputStream os = new FileOutputStream("output.txt");
for (int i = 0; i < bWrite.length; i++) {
os.write(bWrite[i]);
}
os.close();
InputStream is = new FileInputStream("output.txt");
int size = is.available();
for (int j = 0; j < size; j++) {
System.out.print((char)is.read() + " - ");
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------------------------------------------------
// OUTPUT :
//The below code would create file test.txt and would write given numbers in binary format.
DataOutputStream
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
// The DataOutputStream stream let you write the primitives to an output source
// DataOutputStream out = DataOutputStream(OutputStream out);
// Methods
//public final void write(byte[] w, int off, int len)throws IOException
//Public final int write(byte [] b)throws IOException
//(a) public final void writeBooolean()throws IOException,
//(b) public final void writeByte()throws IOException,
//(c) public final void writeShort()throws IOException
//(d) public final void writeInt()throws IOException
//Public void flush()throws IOException
//public final void writeBytes(String s) throws IOException
//NOTES:
//Firstly we have to create file input.txt and put some text in it which are
//both in capital and small letters.
//This example reads lines given in a file input.txt and convert those lines into capital letters
//and finally copies them into another file output.txt.
public class DataOutputStreamDemoo {
public static void main(String[] args) throws IOException {
DataInputStream dIn = new DataInputStream(new FileInputStream("src/input.txt"));
DataOutputStream dOut = new DataOutputStream(new FileOutputStream("output.txt"));
String count;
while((count = dIn.readLine()) != null){
String uString = count.toUpperCase();
System.out.println(uString);
dOut.writeBytes(uString);
}
dIn.close();
dOut.close();
}
}
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
// The DataOutputStream stream let you write the primitives to an output source
// DataOutputStream out = DataOutputStream(OutputStream out);
// Methods
//public final void write(byte[] w, int off, int len)throws IOException
//Public final int write(byte [] b)throws IOException
//(a) public final void writeBooolean()throws IOException,
//(b) public final void writeByte()throws IOException,
//(c) public final void writeShort()throws IOException
//(d) public final void writeInt()throws IOException
//Public void flush()throws IOException
//public final void writeBytes(String s) throws IOException
//NOTES:
//Firstly we have to create file input.txt and put some text in it which are
//both in capital and small letters.
//This example reads lines given in a file input.txt and convert those lines into capital letters
//and finally copies them into another file output.txt.
public class DataOutputStreamDemoo {
public static void main(String[] args) throws IOException {
DataInputStream dIn = new DataInputStream(new FileInputStream("src/input.txt"));
DataOutputStream dOut = new DataOutputStream(new FileOutputStream("output.txt"));
String count;
while((count = dIn.readLine()) != null){
String uString = count.toUpperCase();
System.out.println(uString);
dOut.writeBytes(uString);
}
dIn.close();
dOut.close();
}
}
ByteArrayOutputStream
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
// The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to
// the stream is stored in the buffer.Following constructor creates a buffer of 32 byte:
//OutputStream bOut = new ByteArrayOutputStream()
//OutputStream bOut = new ByteArrayOutputStream(int a)
//Methods
//public void reset()
//public byte[] toByteArray()
//public String toString()
//public void write(int w)
//public void write(byte []b, int of, int len)
//public void writeTo(OutputStream outSt)
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) throws IOException {
System.out.println("Please enter contents: ");
ByteArrayOutputStream bOut = new ByteArrayOutputStream(12);
while(bOut.size() != 10){
bOut.write(System.in.read());
}
byte[] b = bOut.toByteArray();
System.out.println("Print the user entered contents");
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bIn = new ByteArrayInputStream(b);
System.out.println("Converting All the characters to the upper case");
for (int i = 0; i < 1; i++) {
while((c = bIn.read()) != -1){
System.out.println(Character.toUpperCase((char)c));
}
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
// The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to
// the stream is stored in the buffer.Following constructor creates a buffer of 32 byte:
//OutputStream bOut = new ByteArrayOutputStream()
//OutputStream bOut = new ByteArrayOutputStream(int a)
//Methods
//public void reset()
//public byte[] toByteArray()
//public String toString()
//public void write(int w)
//public void write(byte []b, int of, int len)
//public void writeTo(OutputStream outSt)
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) throws IOException {
System.out.println("Please enter contents: ");
ByteArrayOutputStream bOut = new ByteArrayOutputStream(12);
while(bOut.size() != 10){
bOut.write(System.in.read());
}
byte[] b = bOut.toByteArray();
System.out.println("Print the user entered contents");
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bIn = new ByteArrayInputStream(b);
System.out.println("Converting All the characters to the upper case");
for (int i = 0; i < 1; i++) {
while((c = bIn.read()) != -1){
System.out.println(Character.toUpperCase((char)c));
}
}
}
}
FileOutputStream
FileOutputStream is used to create a file and write data into it.
The stream would create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
OutputStream f = new FileOutputStream("C:/java/hello")
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Methods:
public void close() throws IOException{}
protected void finalize()throws IOException {}
public void write(int w)throws IOException{}
public void write(byte[] w)
There are other important output streams available, for more detail you can refer to the following links:
ByteArrayOutputStream
DataOutputStream
DataInputStream
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//The DataInputStreamDemo is used in the context of DataOutputStream and can be used to read primitives.
//InputStream in = DataInputStreamDemo(InputStream in);
// Methods with Description
// public final int read(byte[] r, int off, int len)throws IOException
// Public final int read(byte [] b)throws IOException
//public String readLine() throws IOException
// (a) public final Boolean readBooolean()throws IOException,
// (b) public final byte readByte()throws IOException,
// (c) public final short readShort()throws IOException
// (d) public final Int readInt()throws IOException
// NOTES:
// Firstly we have to create file input.txt and put some text in it which are
// both in capital and small letters.
//This example reads 5 lines given in a file input.txt and convert those lines into capital letters
//and finally copies them into another file output.txt.
public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {
DataInputStream dIn = new DataInputStream(new FileInputStream("src/input.txt"));
DataOutputStream dOut = new DataOutputStream(new FileOutputStream("output.txt"));
String count;
while((count = dIn.readLine()) != null){
String uppercaseString = count.toUpperCase();
System.out.println(uppercaseString); // print the content to the console screen
dOut.writeBytes(uppercaseString + " ,"); // copying the text to the output.txt file
}
dIn.close();
dOut.close();
}
}
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//The DataInputStreamDemo is used in the context of DataOutputStream and can be used to read primitives.
//InputStream in = DataInputStreamDemo(InputStream in);
// Methods with Description
// public final int read(byte[] r, int off, int len)throws IOException
// Public final int read(byte [] b)throws IOException
//public String readLine() throws IOException
// (a) public final Boolean readBooolean()throws IOException,
// (b) public final byte readByte()throws IOException,
// (c) public final short readShort()throws IOException
// (d) public final Int readInt()throws IOException
// NOTES:
// Firstly we have to create file input.txt and put some text in it which are
// both in capital and small letters.
//This example reads 5 lines given in a file input.txt and convert those lines into capital letters
//and finally copies them into another file output.txt.
public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {
DataInputStream dIn = new DataInputStream(new FileInputStream("src/input.txt"));
DataOutputStream dOut = new DataOutputStream(new FileOutputStream("output.txt"));
String count;
while((count = dIn.readLine()) != null){
String uppercaseString = count.toUpperCase();
System.out.println(uppercaseString); // print the content to the console screen
dOut.writeBytes(uppercaseString + " ,"); // copying the text to the output.txt file
}
dIn.close();
dOut.close();
}
}
ByteArrayInputStream
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
// The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream.
//The input source is a byte array.
// There are following forms of constructors to create ByteArrayInputStream objects
// ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
// ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,int off, int len);
// METHODS
// public int read()
// public int read(byte[] r, int off, int len)
// public int available()
// public void mark(int read)
// public long skip(long n)
public class ByteArrayInputNoutputStream {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream(12);
while(bOut.size() != 5){
bOut.write(System.in.read());
}
byte[] b = bOut.toByteArray();
System.out.println("Print all the entered content");
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]+" ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bIn = new ByteArrayInputStream(b);
System.out.println("Converting All the entered Characters to the upper case");
for (int i = 0; i < 1; i++) {
while((c = bIn.read()) != -1){
System.out.println(Character.toUpperCase((char)c));
}
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
// The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream.
//The input source is a byte array.
// There are following forms of constructors to create ByteArrayInputStream objects
// ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
// ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,int off, int len);
// METHODS
// public int read()
// public int read(byte[] r, int off, int len)
// public int available()
// public void mark(int read)
// public long skip(long n)
public class ByteArrayInputNoutputStream {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream(12);
while(bOut.size() != 5){
bOut.write(System.in.read());
}
byte[] b = bOut.toByteArray();
System.out.println("Print all the entered content");
for (int i = 0; i < b.length; i++) {
System.out.print((char)b[i]+" ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bIn = new ByteArrayInputStream(b);
System.out.println("Converting All the entered Characters to the upper case");
for (int i = 0; i < 1; i++) {
while((c = bIn.read()) != -1){
System.out.println(Character.toUpperCase((char)c));
}
}
}
}
FileInputStream
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
InputStream f = new FileInputStream("C:/java/hello");
OR
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
public void close() throws IOException{}
protected void finalize()throws IOException {}
public int read(int r)throws IOException{}
public int read(byte[] r) throws IOException{}
public int available() throws IOException{}
There are other important input streams available, for more detail you can refer to the
following links:
ByteArrayInputStream
DataInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
InputStream f = new FileInputStream("C:/java/hello");
OR
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
public void close() throws IOException{}
protected void finalize()throws IOException {}
public int read(int r)throws IOException{}
public int read(byte[] r) throws IOException{}
public int available() throws IOException{}
There are other important input streams available, for more detail you can refer to the
following links:
ByteArrayInputStream
DataInputStream
Standard Streams
Java provides following three standard streams:
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually
a computer screen is used to standard output stream and represented as System.out.
Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually
a computer screen is used to standard output stream and represented as System.out.
Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
Character Streams
package characterStream;
// Character Streams are used to perform input and output for 16-bit unicode
// Though there are many classes related to character streams but the most frequently used
// classes are , FileReader and FileWriter..
// Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
// here major difference is that FileReader reads two bytes at a time and FileWriter writes
// two bytes at a time.
// NOTES:
// Now let's have a file input.txt with the following content: "This is test for copy file".
// In this case the file is made inside outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStream {
public static void main(String[] args) throws IOException{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("src/input.txt");
fw = new FileWriter("output.txt");
// in this case the out file is made below the system JRE files
int c;
while((c = fr.read()) != -1){
fw.write(c);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fr != null){
fr.close();
}
if(fw != null){
fw.close();
}
}
}
}
// Character Streams are used to perform input and output for 16-bit unicode
// Though there are many classes related to character streams but the most frequently used
// classes are , FileReader and FileWriter..
// Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
// here major difference is that FileReader reads two bytes at a time and FileWriter writes
// two bytes at a time.
// NOTES:
// Now let's have a file input.txt with the following content: "This is test for copy file".
// In this case the file is made inside outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStream {
public static void main(String[] args) throws IOException{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("src/input.txt");
fw = new FileWriter("output.txt");
// in this case the out file is made below the system JRE files
int c;
while((c = fr.read()) != -1){
fw.write(c);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fr != null){
fr.close();
}
if(fw != null){
fw.close();
}
}
}
}
-------------------------------------------input.txt------------------------------------------
This is test for copy file.
-------------------------------------------OUTPUT----------------------------------------
// In this case the file is made inside outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
Byte Stream
package byteStream;
// Stream can be defined as a sequence of data.
// Stream represents an input source and output destination.
// InputStream is used to read data from a source and OutputStream is used for
// writing data to a destination
//Though there are many classes related to character streams but the most frequently used
//classes are , FileInputStream and FileOutputStream..
// Java Byte Stream are used to perform input and output of 8-bit bytes.
// NOTES:
// Now let's have a file input.txt with the following content: "This is test for copy file".
// In this case the file is made inside src/outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("src/input.txt");
fos = new FileOutputStream("src/outputs.txt");
int c ;
while((c = fis.read())!= -1){
fos.write(c);
}
System.out.println(fos); // reference value of the file
}finally{
if (fis!= null) {
fis.close();
}
if (fos!= null) {
fos.close();
}
}
}
}
// Stream can be defined as a sequence of data.
// Stream represents an input source and output destination.
// InputStream is used to read data from a source and OutputStream is used for
// writing data to a destination
//Though there are many classes related to character streams but the most frequently used
//classes are , FileInputStream and FileOutputStream..
// Java Byte Stream are used to perform input and output of 8-bit bytes.
// NOTES:
// Now let's have a file input.txt with the following content: "This is test for copy file".
// In this case the file is made inside src/outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("src/input.txt");
fos = new FileOutputStream("src/outputs.txt");
int c ;
while((c = fis.read())!= -1){
fos.write(c);
}
System.out.println(fos); // reference value of the file
}finally{
if (fis!= null) {
fis.close();
}
if (fos!= null) {
fos.close();
}
}
}
}
-------------------------------------------input.txt------------------------------------------
This is test for copy file.
-------------------------------------------OUTPUT----------------------------------------
// In this case the file is made inside src/outputs.txt .
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
// It reads the bytes data from input.txt and as an output it write the
// same text to output.txt by autogenerating the outputs.txt file.
Java Streams
The java.io package contains nearly every class you might ever need to perform
input and output (I/O)in Java.
All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives,
Object, localized characters, etc.
A stream can be defined as a sequence of data.
The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks.
Java Strings
matches() :
package stringMethods2;
public class Matches {
public static void main(String[] args) {
String str = "Welcome to my hood";
System.out.println(str.matches("(.*)my(.*)"));
System.out.println(str.matches("(.*)my"));
System.out.println(str.matches("my(.*)"));
System.out.println(str.matches("Welcome(.*)"));
}
}
regionMatches() :
package stringMethods2;
// public boolean regionMatches(int toffset, String other, int ooffset, int len)
// or
// regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len)
public class regionMatches {
public static void main(String[] args) {
String str = "Welcome to my hood";
String str2 = "to";
String str3 = "TO";
System.out.println(str.regionMatches(8 , str2 , 0, 2));
System.out.println(str.regionMatches(8 , str3 , 0, 2));
System.out.println(str.regionMatches(true, 8, str3, 0, 2));
}
}
replace() :
package stringMethods2;
// public String replace(char oldChar,char newChar)
public class replace {
public static void main(String[] args) {
String str1 = "Welcome to my tutorial";
System.out.println(str1.replace('m', 'X'));
}
}
replaceAll() :
package stringMethods2;
// public String replaceAll(String regex,String replacement)
public class replaceAll {
public static void main(String[] args) {
String str1 = "welcome to my hood";
System.out.println(str1.replaceAll("(.*)to(.*)", "ReplacedString"));
System.out.println(str1.replaceAll("to(.*)", "ReplacedString"));
System.out.println(str1.replaceAll("(.*)to", "ReplacedString"));
}
}
replaceFirst() :
package stringMethods2;
public class ReplaceFirst {
public static void main(String[] args) {
String name = "Welcome to my hood";
System.out.println(name.replaceFirst("hood", "replacementString"));
}
}
split() :
package stringMethods2;
// public String[] split(String regex,int limit)
// or
// public String[] split(String regex)
public class split {
public static void main(String[] args) {
String str1 =new String( "Welcome to-my hood");
//System.out.println(str1.split("-"));
//System.out.println(str1.split("-",5)); It gives the reference code
for (String string : str1.split("-")) {
System.out.println(string);
}
System.out.println("\n----------------\n");
for(String string2 : str1.split("o", 4)){
System.out.println(string2);
}
}
}
startsWith() :
package stringMethods2;
// public boolean startsWith(String prefix,int toffset)
// or
// public boolean startsWith(String prefix)
public class startsWith {
public static void main(String[] args) {
String str = "Welcome to my hood";
System.out.println(str.startsWith("Welcome"));
System.out.println(str.startsWith("welcome"));
System.out.println(str.startsWith("Welcome",0));
System.out.println(str.startsWith("Welcome",1));
}
}
subSequence() :
package stringMethods2;
// public CharSequence subSequence(int beginIndex,int endIndex)
public class subSequence {
public static void main(String[] args) {
String name = "honey bunny";
System.out.println(name.subSequence(2, 10));
}
}
subString() :
package stringMethods2;
// public String substring(int beginIndex)
// or
// public String substring(int beginIndex,int endIndex)
public class subString {
public static void main(String[] args) {
String str = "Welcome to my hood" ;
System.out.println(str.substring(3));
System.out.println(str.substring(1, 11));
}
}
toCharArray() :
package stringMethods2;
// public char[] ToCharArray()
public class ToCharArray {
public static void main(String[] args) {
String str = new String("Welcome honey.com");
System.out.println(str.toCharArray());
}
}
toUppercase() / toLowercase() :
package stringMethods2;
// public String toLowerCase()
// or
// public String toLowerCase(Locale locale)
// public String toUpperCase()
// or
// public String toUpperCase(Locale locale)
public class toLowerAndUpperCase {
public static void main(String[] args) {
String name = "Bipen";
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
}
}
trim() :
package stringMethods2;
// publicString trim(
// It returns a copy of this string with leading and trailing white space removed, or this string if it
// has no leading or trailing white space.
public class trim {
public static void main(String[] args) {
String str = " Welcome to my hood. ";
System.out.println(str.trim());
}
}
valueOf() :
package stringMethods2;
// This method returns the string representation of the passed argument.
// static String valueOf(boolean b)
// static String valueOf(char c)
// static String valueOf(char[] data)
// static String valueOf(char[] data,int offset,int count)
// static String valueOf(double d)
// static String valueOf(float f)
// static String valueOf(int i)
// static String valueOf(long l)
// static String valueOf(Object obj)
public class ValueOf {
public static void main(String[] args) {
int a = 1;
double b = 2.0 ;
float c = 3f ;
boolean d = true;
char[] ch = {'a','s','d','f','g','h','j','k','l'};
System.out.println(String.valueOf(a));
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(ch));
}
}
package stringMethods2;
public class Matches {
public static void main(String[] args) {
String str = "Welcome to my hood";
System.out.println(str.matches("(.*)my(.*)"));
System.out.println(str.matches("(.*)my"));
System.out.println(str.matches("my(.*)"));
System.out.println(str.matches("Welcome(.*)"));
}
}
regionMatches() :
package stringMethods2;
// public boolean regionMatches(int toffset, String other, int ooffset, int len)
// or
// regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len)
public class regionMatches {
public static void main(String[] args) {
String str = "Welcome to my hood";
String str2 = "to";
String str3 = "TO";
System.out.println(str.regionMatches(8 , str2 , 0, 2));
System.out.println(str.regionMatches(8 , str3 , 0, 2));
System.out.println(str.regionMatches(true, 8, str3, 0, 2));
}
}
replace() :
package stringMethods2;
// public String replace(char oldChar,char newChar)
public class replace {
public static void main(String[] args) {
String str1 = "Welcome to my tutorial";
System.out.println(str1.replace('m', 'X'));
}
}
package stringMethods2;
// public String replaceAll(String regex,String replacement)
public class replaceAll {
public static void main(String[] args) {
String str1 = "welcome to my hood";
System.out.println(str1.replaceAll("(.*)to(.*)", "ReplacedString"));
System.out.println(str1.replaceAll("to(.*)", "ReplacedString"));
System.out.println(str1.replaceAll("(.*)to", "ReplacedString"));
}
}
replaceFirst() :
package stringMethods2;
public class ReplaceFirst {
public static void main(String[] args) {
String name = "Welcome to my hood";
System.out.println(name.replaceFirst("hood", "replacementString"));
}
}
package stringMethods2;
// public String[] split(String regex,int limit)
// or
// public String[] split(String regex)
public class split {
public static void main(String[] args) {
String str1 =new String( "Welcome to-my hood");
//System.out.println(str1.split("-"));
//System.out.println(str1.split("-",5)); It gives the reference code
for (String string : str1.split("-")) {
System.out.println(string);
}
System.out.println("\n----------------\n");
for(String string2 : str1.split("o", 4)){
System.out.println(string2);
}
}
}
startsWith() :
package stringMethods2;
// public boolean startsWith(String prefix,int toffset)
// or
// public boolean startsWith(String prefix)
public class startsWith {
public static void main(String[] args) {
String str = "Welcome to my hood";
System.out.println(str.startsWith("Welcome"));
System.out.println(str.startsWith("welcome"));
System.out.println(str.startsWith("Welcome",0));
System.out.println(str.startsWith("Welcome",1));
}
}
package stringMethods2;
// public CharSequence subSequence(int beginIndex,int endIndex)
public class subSequence {
public static void main(String[] args) {
String name = "honey bunny";
System.out.println(name.subSequence(2, 10));
}
}
subString() :
package stringMethods2;
// public String substring(int beginIndex)
// or
// public String substring(int beginIndex,int endIndex)
public class subString {
public static void main(String[] args) {
String str = "Welcome to my hood" ;
System.out.println(str.substring(3));
System.out.println(str.substring(1, 11));
}
}
package stringMethods2;
// public char[] ToCharArray()
public class ToCharArray {
public static void main(String[] args) {
String str = new String("Welcome honey.com");
System.out.println(str.toCharArray());
}
}
package stringMethods2;
// public String toLowerCase()
// or
// public String toLowerCase(Locale locale)
// public String toUpperCase()
// or
// public String toUpperCase(Locale locale)
public class toLowerAndUpperCase {
public static void main(String[] args) {
String name = "Bipen";
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
}
}
package stringMethods2;
// publicString trim(
// It returns a copy of this string with leading and trailing white space removed, or this string if it
// has no leading or trailing white space.
public class trim {
public static void main(String[] args) {
String str = " Welcome to my hood. ";
System.out.println(str.trim());
}
}
package stringMethods2;
// This method returns the string representation of the passed argument.
// static String valueOf(boolean b)
// static String valueOf(char c)
// static String valueOf(char[] data)
// static String valueOf(char[] data,int offset,int count)
// static String valueOf(double d)
// static String valueOf(float f)
// static String valueOf(int i)
// static String valueOf(long l)
// static String valueOf(Object obj)
public class ValueOf {
public static void main(String[] args) {
int a = 1;
double b = 2.0 ;
float c = 3f ;
boolean d = true;
char[] ch = {'a','s','d','f','g','h','j','k','l'};
System.out.println(String.valueOf(a));
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(ch));
}
}
Subscribe to:
Comments (Atom)
































