Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java IO

The document discusses Java IO streams and how they are used to perform input and output operations in Java. It describes the different types of streams - byte streams and character streams. It provides details on important stream classes like InputStream, OutputStream, Reader, Writer etc. and how they are used. It also discusses the differences between byte streams and character streams. Finally, it talks about the Java File class and some common methods used for file operations.

Uploaded by

memonaasim1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java IO

The document discusses Java IO streams and how they are used to perform input and output operations in Java. It describes the different types of streams - byte streams and character streams. It provides details on important stream classes like InputStream, OutputStream, Reader, Writer etc. and how they are used. It also discusses the differences between byte streams and character streams. Finally, it talks about the Java File class and some common methods used for file operations.

Uploaded by

memonaasim1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Java IO Streams

Java IO Streams
 Java performs I/O through Streams. A Stream is linked to a
physical layer by java I/O system to make input and output
operation in java. In general, a stream means continuous flow of
data. Streams are clean way to deal with input/output without
having every part of your code understand the physical.
 Java encapsulates Stream under java.io package. Java defines two
types of streams. They are,
 Byte Stream : It provides a convenient means for handling input
and output of byte.
 Character Stream : It provides a convenient means for handling
input and output of characters. Character stream uses Unicode and
therefore can be internationalized.
Java Byte Stream Classes
 Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
 Some important Byte stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStrea Used for Buffered Output Stream.
m These classes define several key
DataInputStream Contains method for reading java standard datatype methods. Two most important are

DataOutputStream An output stream that contain method for writing java read() : reads byte of data.
standard data type write() : Writes byte of data.
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that
contain print() and println() method
Java Character Stream Classes

 Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
 Some important Character stream classes

Stream class Description


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


Byte Stream vs Character Streams

Byte Stream Character Stream


They process the data character by
They process the data byte by byte.
character.
They read/write data 8 bits They read/write data 16 bits
maximum at a time. maximum at a time.
They are most suitable to process They are most suitable to process
binary files. text files.
All byte stream classes in Java are All character stream classes in Java
descendants of InputStream and are descendants of Reader and
OutputStream. Writer.
Reading Console Input
 We use the object of BufferedReader class to take inputs from the keyboard.

class CharRead
{
public static void main( String args[])
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
Java File class

 In Java, File class is used for the representation of files or


directory pathname. Because of the names of files and
directory have different formats on a different platform.
The path of a file can be absolute or relative. There are
many methods of file classes which can be used for
creating, reading, deleting or renaming a file.
 How to Create a File Object?
 A File object is created by passing in a string that represents the
name of a file, a String, or another File object. For example,
 File a = new File("/usr/local/bin/geeks");
 This defines an abstract file name for the geeks file in the
directory /usr/local/bin. This is an absolute abstract file name
Methods of File Class in Java
Method Description

createNewFile() It is used for creating a new file, which is empty and has an abstract pathname.

canWrite() It is used to check whether the application can modify a file which has an abstract path.

canExecute() It is used to check whether the application can execute a file which has an abstract path.

canRead() It is used to check whether the application can read a file which has an abstract path

isAbsolute() It is used to check whether the abstract pathname is absolute or not.

isDirectory() It is used to check whether the file with abstract pathname is a directory.

isFile() It is used to check whether the file with abstract pathname is a file.

getName() It is used to get the name of the file.


getParent() It is used to get the name of the Parent file
toPath() It is used to get objects of java.nio.file.Path.
toURI() It is used to create a URL of a file with abstract pathname.
listFiles() It is used for getting an array of the abstract pathname.
getFreeSpace() It is used for getting the number of unallocated bytes.
list(FilenameFilter It is used for getting an array of string with the name of the file which have abstract pathname.
filter)
mkdir() It is used to create directory name.
Example : Creating a File

package main;
import java.io.*;
public class Main {
public static void main( String args[])
{
try
{
File Obj = new File("FileDemo.txt");
if (Obj.createNewFile()) {
System.out.println("******File created******");
System.out.println("Name of the file = " + Obj.getName());
}
else{
System.out.println("File already exists.");
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
Java File Class Examples
public class Main {
public static void main( String args[]) throws IOException
{
String fname = "FileDemo.txt";
// pass the filename or directory name to File
// object
File f = new File(fname);
// apply File class methods on File object
System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"+ f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());
if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
Different ways of Reading a text file in Java
 Methods:
 Using BufferedReader class
 Using Scanner class
 Using File Reader class
 Reading the whole file in a List
 Read a text file as String
BufferedReader class for Reading text file
 This method reads text from a character-input stream. It does
buffer for efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be
used. The default is large enough for most purposes. In
general, each read request made of a Reader causes a
corresponding read request to be made of the underlying
character or byte stream. It is therefore advisable to wrap a
BufferedReader around any Reader whose read() operations
may be costly, such as FileReaders and InputStreamReaders as
shown below as follows:
 Syntax
 BufferedReader in = new BufferedReader(Reader in, int size);
BufferedReader class for Reading text file

package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
File file = new File("TEST.txt");
BufferedReader br= new BufferedReader(new FileReader(file));
String st;
// Condition holds true till
// there is character in a string
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
FileReader class for Reading text file

package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
FileReader fr = new FileReader("test.txt");
int i;
// Holds true till there is nothing to read
while ((i = fr.read()) != -1)
// Print all the content of a file
System.out.print((char)i);
}
}
Scanner class for reading text file
 A simple text scanner that can parse primitive types and strings using regular
expressions. A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next methods.
package main;
import java.io.*;
import java.util.*;
public class Main {
public static void main( String args[]) throws IOException
{
File f = new File("test.txt");
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
}
}
Without using loops
package main;
import java.io.*;
import java.util.*;
public class Main {
public static void main( String args[]) throws
IOException
{
File f = new File("test.txt");
Scanner sc=new Scanner(f);
sc.useDelimiter("#");
System.out.println(sc.next());
}
}
Reading the whole file in a List
package main;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Main {
public static void main( String args[]) throws IOException
{
List<String> list=Collections.emptyList();
list=Files.readAllLines(Paths.get("FileDemo.txt"),
StandardCharsets.UTF_8);
Iterator<String> i=list.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Read a text file as String

package main;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main( String args[]) throws IOException
{
String s="";
s=new String(Files.readAllBytes(Paths.get("FileDemo.txt")));
System.out.println(s);
}
package main;
}
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main( String args[]) throws
IOException
{
Path p=Path.of("FileDemo.txt");
String s=Files.readString(p);
System.out.println(s);
}
}
Java Program to Write into a File

 There are many ways to write into a file in Java as


there are many classes and methods which can fulfill the
goal as follows:
 Using writeString() method
 Using FileWriter Class
 Using BufferedWriter Class
 Using FileOutputStream Class
Using writeString() method
package main;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main( String args[]) throws
IOException
{
String text = "Welcome to Java\nHappy Learning!";
Path fileName = Path.of("FileDemo.txt");
Files.writeString(fileName, text);
String file_content = Files.readString(fileName);
System.out.println(file_content);
}
}
Using FileWriter Class

 If the content of the file is short, then using the FileWriter class
to write in the file is another better option. It also writes the
stream of characters as the content of the file like writeString()
method. The constructor of this class defines the default
character encoding and the default buffer size in bytes.
 The following below example illustrates the use of the
FileWriter class to write content into a file. It requires creating
the object of the FileWriter class with the filename to write
into a file. Next, the write() method is used to write the value
of the text variable in the file. If any error occurs at the time of
writing the file, then an IOException will be thrown, and the
error message will be printed from the catch block.
Using FileWriter Class
package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
String text = "Computer Science Portal\nnext line\nanother";
FileWriter fWriter = new FileWriter(
"FileDemo.txt");
fWriter.write(text);
System.out.println(text);
fWriter.close();
System.out.println(
"File is created successfully with the content.");
}
}
Using BufferedWriter Class
 It is used to write text to a character-output stream. It has a default buffer
size, but a large buffer size can be assigned. It is useful for writing
characters, strings, and arrays. It is better to wrap this class with any writer
class for writing data to a file if no prompt output is required.
package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
String text = "Computer Science Portal\nnext line\nanother";
FileWriter fWriter = new FileWriter("Newone.txt");
BufferedWriter b=new BufferedWriter(fWriter);
b.write(text);
System.out.println(text);
b.close();
System.out.println(
"File is created successfully with the content.");
}
}
Using FileOutputStream Class

 It is used to write raw stream data to a file. FileWriter and BufferedWriter


classes are used to write only the text to a file, but the binary data can be
written by using the FileOutputStream class.

package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
String text = "Computer Science Portal\nnext line\nanother";
FileOutputStream f=new FileOutputStream("second.txt");
byte [] arr=text.getBytes();
f.write(arr);
System.out.println(
"File is created successfully with the content.");
}
}
Delete a File Using Java
package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
File file = new File("second.txt");
if (file.delete()) {
System.out.println("File deleted successfully");
}
else {
System.out.println("Failed to delete the file");
}
}
}
Using java.nio.file.files.deleteifexists(Path p)
method defined in Files package

 Syntax:
 public static boolean deleteIfExists(Path path) throws IOException
 Parameters: path – the path to the file to delete
 Returns: It returns true if the file was deleted by this method;
false if it could not be deleted because it did not exist.
 Throws:
 DirectoryNotEmptyException – if the file is a directory and could not
otherwise be deleted because the directory is not empty (optional
specific exception)
 IOException – if an I/O error occurs.
package main;
import java.io.*;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
public class Main {
public static void main( String args[]) throws IOException
{
try {
Files.deleteIfExists(Paths.get("myfile.txt"));
}
catch (NoSuchFileException e) {
System.out.println(
"No such file/directory exists");
}
catch (DirectoryNotEmptyException e) {
System.out.println("Directory is not empty.");
}
catch (Exception e) {
System.out.println("Invalid permissions.");
}

System.out.println("Deletion successful.");
}
}
Changing File Permissions
A file in Java can have any combination of the following permissions:
•Executable
•Readable
•Writable
Here are methods to change the permissions associated with a file as depicted in a tabular
format below as follows:

Method Action Performed


Set the owner’s execute permission for this abstract
setExecutable()
pathname

Set the owner’s read permission for this abstract


setReadable()
pathname

Set the owner’s write permission for this abstract


setWritable()
pathname
Example: Writing in a file

package main;
import java.io.*;
public class Main {
public static void main( String args[]) throws IOException
{
FileWriter f=new FileWriter("FileDemo.txt");
f.write("writing something to the file");
f.close();
}
}
Example : Reading a file

package main;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main( String args[]) throws IOException
{
File f=new File("Filedemo.txt");
Scanner s=new Scanner(f);
while(s.hasNext())
{
System.out.println(s.nextLine());
}
}
}
Program to read from a file using BufferedReader class

package main;
import java.io.*;
public class Main {
public static void main( String args[])
{
try
{
File fl = new File("myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Program to read from a file using BufferedReader class
package main;
import java.io.*;
public class Main {
public static void main( String args[])
{
try
{
File fl = new File("myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
Explore

 https://www.geeksforgeeks.org/filewriter-class-in-java/?ref=lbp

You might also like