File I/O in Java

 ### File I/O in Java


Java provides several classes and methods for reading from and writing to files. These classes are part of the `java.io` package and offer both byte-oriented and character-oriented I/O operations. Here's a detailed guide on handling file input and output in Java.


#### Key Classes


1. **File**: Represents a file or directory path in an abstract way.

2. **FileInputStream** and **FileOutputStream**: Byte-oriented classes for reading from and writing to files.

3. **FileReader** and **FileWriter**: Character-oriented classes for reading from and writing to files.

4. **BufferedReader** and **BufferedWriter**: Provide buffering for character-oriented streams.

5. **Scanner** and **PrintWriter**: Simplify reading and writing with various utility methods.


#### 1. Using the `File` Class


The `File` class is used to create and delete files and directories, and to obtain file metadata.


Example:

```java

import java.io.File;

import java.io.IOException;


public class FileExample {

    public static void main(String[] args) {

        File file = new File("example.txt");


        try {

            // Create a new file

            if (file.createNewFile()) {

                System.out.println("File created: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }


            // Get file information

            if (file.exists()) {

                System.out.println("File name: " + file.getName());

                System.out.println("Absolute path: " + file.getAbsolutePath());

                System.out.println("Writeable: " + file.canWrite());

                System.out.println("Readable: " + file.canRead());

                System.out.println("File size in bytes: " + file.length());

            }


            // Delete the file

            if (file.delete()) {

                System.out.println("Deleted the file: " + file.getName());

            } else {

                System.out.println("Failed to delete the file.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

```


#### 2. Byte-Oriented I/O


##### Reading from a File using `FileInputStream`

```java

import java.io.FileInputStream;

import java.io.IOException;


public class FileInputStreamExample {

    public static void main(String[] args) {

        try (FileInputStream fis = new FileInputStream("example.txt")) {

            int content;

            while ((content = fis.read()) != -1) {

                System.out.print((char) content);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


##### Writing to a File using `FileOutputStream`

```java

import java.io.FileOutputStream;

import java.io.IOException;


public class FileOutputStreamExample {

    public static void main(String[] args) {

        String data = "Hello, World!";

        try (FileOutputStream fos = new FileOutputStream("example.txt")) {

            fos.write(data.getBytes());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


#### 3. Character-Oriented I/O


##### Reading from a File using `FileReader`

```java

import java.io.FileReader;

import java.io.IOException;


public class FileReaderExample {

    public static void main(String[] args) {

        try (FileReader fr = new FileReader("example.txt")) {

            int content;

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

                System.out.print((char) content);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


##### Writing to a File using `FileWriter`

```java

import java.io.FileWriter;

import java.io.IOException;


public class FileWriterExample {

    public static void main(String[] args) {

        String data = "Hello, World!";

        try (FileWriter fw = new FileWriter("example.txt")) {

            fw.write(data);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


#### 4. Buffered I/O


##### Reading from a File using `BufferedReader`

```java

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {

            String line;

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

                System.out.println(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


##### Writing to a File using `BufferedWriter`

```java

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;


public class BufferedWriterExample {

    public static void main(String[] args) {

        String data = "Hello, World!";

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {

            bw.write(data);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

```


#### 5. Using `Scanner` and `PrintWriter`


##### Reading from a File using `Scanner`

```java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;


public class ScannerExample {

    public static void main(String[] args) {

        try {

            File file = new File("example.txt");

            Scanner scanner = new Scanner(file);


            while (scanner.hasNextLine()) {

                String line = scanner.nextLine();

                System.out.println(line);

            }

            scanner.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        }

    }

}

```


##### Writing to a File using `PrintWriter`

```java

import java.io.FileNotFoundException;

import java.io.PrintWriter;


public class PrintWriterExample {

    public static void main(String[] args) {

        String data = "Hello, World!";

        try (PrintWriter pw = new PrintWriter("example.txt")) {

            pw.println(data);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        }

    }

}

```


#### Conclusion


File I/O in Java is made simple and flexible with the classes provided in the `java.io` package. Depending on the specific needs of your application, you can choose byte-oriented or character-oriented streams, and use buffered streams for more efficient I/O operations. Understanding these basic file operations will allow you to read from and write to files effectively in your Java programs.

Comments

Popular posts from this blog

Advanced Java Concepts