Skip to content

Latest commit

 

History

History
719 lines (489 loc) · 12.9 KB

File metadata and controls

719 lines (489 loc) · 12.9 KB

পাঠ ১০: জাভা এন আই/ও

  • পাথ
  • ক্রিয়েটিং পাথ
  • রিট্রাইভিং পাথ
  • ডিরেকরি এবং ট্রি
  • ফাইন্ডিং ফাইল ইন ডিরেক্টরি
  • ওয়াকিং থ্রু ডিরেক্টরি
  • ফাইল ক্রিয়েট এবং ডিলেট করা
  • দ্রুত ফাইল রিড এবং ক্রিয়েট করা
  • অ্যাসিঙ্ক্রোনাস আই/ও
  • সারসংক্ষেপ

Java NIO (New Input/Output) হলো Java-এর আধুনিক ফাইল, ডিরেক্টরি এবং নেটওয়ার্ক I/O API। এটি Java 7 থেকে আরও শক্তিশালী হয়েছে java.nio.file প্যাকেজের মাধ্যমে। NIO ব্যবহার করে বড় ফাইল দ্রুত প্রসেস করা, ডিরেক্টরি ট্রাভার্স করা, অ্যাসিঙ্ক্রোনাস অপারেশন চালানো এবং ফাইল সিস্টেমের উপর উন্নত নিয়ন্ত্রণ পাওয়া যায়।


১. Path

Path হলো কোনো ফাইল বা ডিরেক্টরির অবস্থান (location) নির্দেশ করার জন্য ব্যবহৃত একটি ইন্টারফেস।

পুরনো Java IO-তে File ক্লাস ব্যবহার করা হতো, কিন্তু NIO-তে Path বেশি শক্তিশালী।

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("data.txt");

        System.out.println(path);
    }
}

আউটপুট:

data.txt

Path কেন ব্যবহার করবো?

Path ব্যবহার করে—

  • ফাইলের অবস্থান জানা যায়
  • ডিরেক্টরি নেভিগেট করা যায়
  • ফাইলের নাম বের করা যায়
  • Parent ডিরেক্টরি পাওয়া যায়
  • Absolute Path বের করা যায়

২. Creating Path

Path তৈরির জন্য সাধারণত Paths.get() বা Path.of() ব্যবহার করা হয়।

Relative Path

Path path = Path.of("documents/file.txt");

এটি বর্তমান working directory থেকে গণনা করবে।


Absolute Path

Windows:

Path path = Path.of("C:/Users/Admin/file.txt");

Linux:

Path path = Path.of("/home/admin/file.txt");

Multiple Parts দিয়ে Path

Path path = Path.of("users", "admin", "file.txt");

ফলাফল:

users/admin/file.txt

অপারেটিং সিস্টেম অনুযায়ী separator ব্যবহার হবে।


৩. Retrieving Path Information

Path থেকে বিভিন্ন তথ্য বের করা যায়।

Path path = Path.of("documents/report.pdf");

File Name

System.out.println(path.getFileName());

আউটপুট:

report.pdf

Parent Directory

System.out.println(path.getParent());

আউটপুট:

documents

Root

System.out.println(path.getRoot());

Windows এ:

C:\

Name Count

System.out.println(path.getNameCount());

আউটপুট:

2

নির্দিষ্ট অংশ বের করা

System.out.println(path.getName(0));
System.out.println(path.getName(1));

আউটপুট:

documents
report.pdf

Absolute Path

System.out.println(path.toAbsolutePath());

উদাহরণ:

C:\Projects\documents\report.pdf

Normalize Path

Path path = Path.of("docs/../file.txt");

System.out.println(path.normalize());

আউটপুট:

file.txt

৪. Directory এবং Tree

ফাইল সিস্টেম একটি Tree Structure অনুসরণ করে।

উদাহরণ:

Project
│
├── src
│   ├── Main.java
│   └── Utils.java
│
├── resources
│   └── config.properties
│
└── README.md

এখানে:

  • Project = Root Directory
  • src = Child Directory
  • Main.java = File Node

Directory তৈরি

import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {

        Path path = Path.of("myFolder");

        Files.createDirectory(path);

        System.out.println("Directory created");
    }
}

Nested Directory তৈরি

Files.createDirectories(
        Path.of("data/users/admin"));

ফলাফল:

data
 └─ users
     └─ admin

৫. Finding Files in Directory

ডিরেক্টরির মধ্যে নির্দিষ্ট ফাইল খুঁজে বের করা যায়।


Files.list()

Files.list(Path.of("."))
     .forEach(System.out::println);

আউটপুট:

Main.java
data.txt
users

Filter ব্যবহার

শুধুমাত্র .txt ফাইল খুঁজতে:

Files.list(Path.of("."))
     .filter(file -> file.toString().endsWith(".txt"))
     .forEach(System.out::println);

Files.find()

Files.find(
        Path.of("."),
        5,
        (path, attr) -> path.toString().endsWith(".java")
)
.forEach(System.out::println);

এখানে:

  • ৫ = সর্বোচ্চ depth
  • .java ফাইল খুঁজবে

৬. Walking Through Directory

সম্পূর্ণ ডিরেক্টরি Tree ঘুরে দেখা।


Files.walk()

Files.walk(Path.of("."))
     .forEach(System.out::println);

উদাহরণ:

.
src
src/Main.java
src/Test.java
resources
resources/config.properties

Depth নির্ধারণ

Files.walk(Path.of("."), 2)
     .forEach(System.out::println);

Java Files খুঁজে বের করা

Files.walk(Path.of("."))
     .filter(path ->
             path.toString().endsWith(".java"))
     .forEach(System.out::println);

File Visitor

বড় Directory Tree এর জন্য FileVisitor ব্যবহার করা হয়।

import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class MyVisitor
        extends SimpleFileVisitor<Path> {

    @Override
    public FileVisitResult visitFile(
            Path file,
            BasicFileAttributes attrs) {

        System.out.println(file);

        return FileVisitResult.CONTINUE;
    }
}

ব্যবহার:

Files.walkFileTree(
        Path.of("."),
        new MyVisitor());

৭. File Create এবং Delete


File Create

Path file = Path.of("notes.txt");

Files.createFile(file);

Write Data

Files.writeString(
        file,
        "Hello Java NIO");

Read Data

String content =
        Files.readString(file);

System.out.println(content);

Delete File

Files.delete(file);

Delete যদি থাকে

Files.deleteIfExists(file);

Temporary File

Path temp =
        Files.createTempFile(
                "test",
                ".txt");

System.out.println(temp);

Temporary Directory

Path tempDir =
        Files.createTempDirectory(
                "demo");

System.out.println(tempDir);

৮. দ্রুত File Read এবং Write

NIO-এর অন্যতম সুবিধা হলো দ্রুত File Processing।


Read All Lines

List<String> lines =
        Files.readAllLines(
                Path.of("data.txt"));

for(String line : lines) {
    System.out.println(line);
}

Write All Lines

List<String> data =
        List.of(
                "Java",
                "Python",
                "Go");

Files.write(
        Path.of("languages.txt"),
        data);

Byte Array Read

byte[] bytes =
        Files.readAllBytes(
                Path.of("image.jpg"));

Byte Array Write

Files.write(
        Path.of("copy.jpg"),
        bytes);

Buffered Reader

বড় ফাইলের জন্য:

BufferedReader reader =
        Files.newBufferedReader(
                Path.of("data.txt"));

String line;

while((line = reader.readLine()) != null) {
    System.out.println(line);
}

Buffered Writer

BufferedWriter writer =
        Files.newBufferedWriter(
                Path.of("output.txt"));

writer.write("Hello");
writer.close();

৯. Asynchronous I/O

Asynchronous I/O এমন একটি পদ্ধতি যেখানে I/O কাজ চলাকালীন Main Thread ব্লক হয় না।

এটি বড় ফাইল বা Server Application-এর জন্য খুব গুরুত্বপূর্ণ।


AsynchronousFileChannel

import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;

public class Main {

    public static void main(String[] args)
            throws Exception {

        AsynchronousFileChannel channel =
                AsynchronousFileChannel.open(
                        Path.of("data.txt"),
                        StandardOpenOption.READ);

        ByteBuffer buffer =
                ByteBuffer.allocate(1024);

        channel.read(
                buffer,
                0);

        Thread.sleep(1000);

        buffer.flip();

        while(buffer.hasRemaining()) {
            System.out.print(
                    (char) buffer.get());
        }

        channel.close();
    }
}

CompletionHandler ব্যবহার

channel.read(
        buffer,
        0,
        buffer,
        new CompletionHandler<Integer, ByteBuffer>() {

            @Override
            public void completed(
                    Integer result,
                    ByteBuffer buffer) {

                System.out.println(
                        "Read completed");
            }

            @Override
            public void failed(
                    Throwable exc,
                    ByteBuffer buffer) {

                System.out.println(
                        "Read failed");
            }
        });

Asynchronous Write

AsynchronousFileChannel channel =
        AsynchronousFileChannel.open(
                Path.of("log.txt"),
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE);

ByteBuffer buffer =
        ByteBuffer.wrap(
                "Hello NIO".getBytes());

channel.write(buffer, 0);

Java IO বনাম Java NIO

Feature Java IO Java NIO
API পুরনো আধুনিক
Performance কম বেশি
Non-blocking না হ্যাঁ
Async Support না হ্যাঁ
Large File ধীর দ্রুত
File Tree Walk না হ্যাঁ
Path API না হ্যাঁ

বাস্তব ব্যবহার

Java NIO ব্যবহার করা হয়:

  • Web Server
  • REST API
  • Spring Boot Application
  • Log Processing
  • File Upload System
  • Cloud Storage
  • Backup Software
  • IDE Development
  • Search Engine
  • Big Data Processing

সারসংক্ষেপ

এই পাঠে আমরা শিখলাম:

  • Path কী এবং কিভাবে তৈরি করতে হয়
  • Path থেকে তথ্য বের করা
  • Directory এবং File Tree Structure
  • Files খুঁজে বের করা (list, find)
  • Directory Walk করা (walk, walkFileTree)
  • File Create, Read, Write, Delete করা
  • দ্রুত File Processing (readAllLines, readAllBytes)
  • Buffered Reader/Writer ব্যবহার
  • Asynchronous I/O এবং AsynchronousFileChannel
  • Java IO ও Java NIO-এর পার্থক্য

Java NIO হলো আধুনিক Java অ্যাপ্লিকেশনে ফাইল ও ডিরেক্টরি ব্যবস্থাপনার সবচেয়ে শক্তিশালী উপায়। Spring Boot, Microservices, Cloud Application এবং High-Performance Server তৈরিতে NIO সম্পর্কে ভালো ধারণা থাকা অত্যন্ত গুরুত্বপূর্ণ।