Java IO
Java IO
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.
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
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
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
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.
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
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
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:
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