ADV Java
ADV Java
Types of File:
Text File
Binary File
Text File contains only textual data. Text files may be saved in
either a plain text (.TXT) format and rich text (.RTF) format like files
in our Notepad while Binary Files contains both textual data and
custom binary data like font size, text color and text style etc.
import java.io.File;
File f = null;
String[] strs = {"test.txt", "/test.txt"};
try{
// for each string in string array
for(String s:strs )
{
// create new file
f= new File(s);
// prints
System.out.println(" is executable: "+ bool);
// print
System.out.println("File can be writing: "+w);
// print
System.out.println("File can be read: "+r);
}
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}
}
}
import java.io.File;
File f = null;
Boolean bool = false;
try {
// create new file
f = new File ("test.txt");
// prints
System.out.println ("File deleted: "+bool);
// createNewFile () is invoked
System.out.println ("createNewFile() method is invoked");
// print
System.out.println ("File deleted: "+bool);
}
catch(Exception e){
// if any error occurs
e.printStackTrace ();
}
}
}
import java.io.File;
File f = null;
File f1 = null;
try{
// create new files
f = new File("test.txt");
f1 = new File("File/test1.txt");
}catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.File;
File f = null;
String path;
boolean bool = false;
try{
// create new file
f = new File("c.txt");
// prints
System.out.println (path+" is file? "+ bool);
// prints
System.out.println (path+" is Directory? "+p);
// prints
System.out.println (path+" is Hidden? "+h);
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce the output based on
the input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with
console.
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
Method Description
InputStream class
Method Description
1) public abstract int reads the next byte of data from the input
read()throws IOException: stream.It returns -1 at the end of file.
If you have to write primitive values then use FileOutputStream.Instead, for character-
oriented data, prefer FileWriter.But you can write byte-oriented as well as character-
oriented data.
It should be used to read byte-oriented data for example to read image, audio, video etc.
1. import java.io.*;
2. class C{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin=new FileInputStream("C.java");
5. FileOutputStream fout=new FileOutputStream("M.java");
6. int i=0;
7. while((i=fin.read())!=-1){
8. fout.write((byte)i);
9. }
10. fin.close();
11. }
12. }
Constructor Description
ByteArrayOutputStream() creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if
necessary.
Method Description
3) public void write(byte[] b) throws writes byte array into this stream.
IOException
1. import java.io.*;
2. class S{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("f1.txt");
5. FileOutputStream fout2=new FileOutputStream("f2.txt");
6.
7. ByteArrayOutputStream bout=new ByteArrayOutputStream();
8. bout.write(139);
9. bout.writeTo(fout1);
10. bout.writeTo(fout2);
11.
12. bout.flush();
13. bout.close();//has no effect
14. System.out.println("success...");
15. }
16. }
success...
Java SequenceInputStream class
Java SequenceInputStream class is used to read data from multiple streams. It reads data
of streams one by one.
Constructor Description
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileinputStream fin1=new FileinputStream("f1.txt");
5. FileinputStream fin2=new FileinputStream("f2.txt");
6.
7. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
8. int i;
9. while((i=sis.read())!=-1){
10. System.out.println((char)i);
11. }
12. sis.close();
13. fin1.close();
14. fin2.close();
15. }
16. }
If we need to read the data from more than two files, we need to have these information
in the Enumeration object. Enumeration object can be get by calling elements method of
the Vector class. Let's see the simple example where we are reading the data from the 4
files.
1. import java.io.*;
2. import java.util.*;
3.
4. class B{
5. public static void main(String args[])throws IOException{
6.
7. //creating the FileInputStream objects for all the files
8. FileInputStream fin=new FileInputStream("A.java");
9. FileInputStream fin2=new FileInputStream("abc2.txt");
10. FileInputStream fin3=new FileInputStream("abc.txt");
11. FileInputStream fin4=new FileInputStream("B.java");
12.
13. //creating Vector object to all the stream
14. Vector v=new Vector();
15. v.add(fin);
16. v.add(fin2);
17. v.add(fin3);
18. v.add(fin4);
19.
20. //creating enumeration object by calling the elements method
21. Enumeration e=v.elements();
22.
23. //passing the enumeration object in the constructor
24. SequenceInputStream bin=new SequenceInputStream(e);
25. int i=0;
26.
27. while((i=bin.read())!=-1){
28. System.out.print((char)i);
29. }
30.
31. bin.close();
32. fin.close();
33. fin2.close();
34. }
35. }
1. import java.io.*;
2. class Test{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("f1.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Sachin is my favourite player";
7. byte b[]=s.getBytes();
8. bout.write(b);
9.
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:
success...
1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("f1.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.println((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }
Output:
Sachin is my favourite player
Java has suggested not to use the FileInputStream and FileOutputStream classes if you
have to read and write the textual information.
Constructor Description
FileWriter(File file) creates a new file. It gets file name in File object.
Method Description
1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("success");
10. }
11. }
Output:
success...
Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If
file) file doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read
mode. If file doesn't exist, it throws FileNotFoundException.
Methods of FileReader class
Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the end of
file.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("abc.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.println((char)i);
8.
9. fr.close();
10. }
11. }
Output:
my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements
the Appendable interface. Its buffer automatically grows when data is written in this stream.
Calling the close() method on this object has no effect.
InputStreamReader
Console
Scanner
DataInputStream etc.
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
Example of reading data from keyboard by InputStreamReader
and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while(name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Method Description
1) public String readLine() is used to read a single line of text from the
console.
System class provides a static method console() that returns the unique instance of Console
class.
1. Console c=System.console();
Output:
Enter your name: james gosling
Welcome james gosling
Output:
Enter password:
Password is: sonoo
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }
Output:
1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}
Output:
10
tea
20
coffee
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream
class automatically flushes the data so there is no need to call flush() method. Moreover, its
methods don't throw IOException.
There are many methods in PrintStream class. Let's see commonly used methods of
PrintStream class:
public void print(boolean b): it prints the specified boolean value.
public void print(char c): it prints the specified char value.
public void print(char[] c): it prints the specified character array values.
public void print(int i): it prints the specified int value.
public void print(long l): it prints the specified long value.
public void print(float f): it prints the specified float value.
public void print(double d): it prints the specified double value.
public void print(String s): it prints the specified string value.
public void print(Object obj): it prints the specified object value.
public void println(boolean b): it prints the specified boolean value and
terminates the line.
public void println(char c): it prints the specified char value and terminates the
line.
public void println(char[] c): it prints the specified character array values and
terminates the line.
public void println(int i): it prints the specified int value and terminates the
line.
public void println(long l): it prints the specified long value and terminates the
line.
public void println(float f): it prints the specified float value and terminates the
line.
public void println(double d): it prints the specified double value and
terminates the line.
public void println(String s): it prints the specified string value and terminates
the line./li>
public void println(Object obj): it prints the specified object value and
terminates the line.
public void println(): it terminates the line only.
public void printf(Object format, Object... args): it writes the formatted
string to the current stream.
public void printf(Locale l, Object format, Object... args): it writes the
formatted string to the current stream.
public void format(Object format, Object... args): it writes the formatted
string to the current stream using specified format.
public void format(Locale l, Object format, Object... args): it writes the
formatted string to the current stream using specified format.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});