Java I/O

Java I/O 


Java I/O


👉Definition: Java I/O is the ability to read and write data from/to File System/network/database/memory/Console etc.

For reading writing we need to make OS call and making OS call we need libraries Known as java.io.* libraries.

There are two I/O libraries java.io & java.nio (nio- non-synchronous I/O).

👉Read/Write character

📑Read

FileReader fr = new FileReader("C:/test.txt");

fr.read();

//if file path already exists and we want to append.

FileWriter fw = new FileWriter("C:/test.txt", true);


🖋 Read from in.txt file and write out.txt to file



 FileReader fr;

 FileWriter fw;

 try{

 fr = new FileReader("C:/in.txt");

 fw = new FileWriter("C:/out.txt");

 int x

    while((x = fr.read()) != -1){

    fw.write(x);

    }

 }catch(IOException e){

            e.printStackTrace();

 }

 finally{

 try{

 if(fr != null )

    fr.close();

 }catch(IOException e){

            e.printStackTrace();

 }

try{

if(fw != null)

    fw.close();

}catch(IOException e){

            e.printStackTrace();

 }

 }




🤔 The above code will work fine but it is bad code because it is reading each character at a time so to avoid these we will use buffering.

BufferReadFile


 File fi = new file("path");

 BufferedReader br = null;

 try{

    br = new BufferedReader(new FileReader(fi));

    String line;

    while((line = br.readLine()) != null)

    {

            System.out.println(line);

    }

 }catch(IoException e){

 e.printStackTrace();

 }finally{ try{

 if(br != null)

    br.close();

 }catch(IOException e){

        e.printStackTrace();

 }

 }


BufferedWriter


 File fi = new file("path");

 File fo = new file("path");

 BufferedReader br = null;

 BufferedWriter bw = null;

 try{

    br = new BufferedReader(new FileReader(fi));

    bw = new BufferedWriter(new FileWriter(fo, true));

    String line;

    while((line = br.readLine()) != null)

    {

            System.out.println(line);

            bw.append(line);

            bw.newLine();

    }

 }catch(IoException e){

 e.printStackTrace();

 }finally{ try{

 if(bw != null)

    bw.close();

 }catch(IOException e){

        e.printStackTrace();

 }

 try{

 if(br != null)

    br.close();

 }catch(IOException e){

        e.printStackTrace();

 }

 }

No comments:

For Query and doubts!

Powered by Blogger.