জাভাতে ফাইলের মাঝপথের একটি লাইন সরাসরি ওভাররাইট করা সহজ নয় (কারণ ফাইল সিকোয়েনশিয়াল স্টোরেজ)। সাধারণ পদ্ধতি: পুরো ফাইল পড়ে মেমোরিতে আনা → নির্দিষ্ট লাইন রিপ্লেস করা → পুরো ফাইল নতুন করে লিখা।
পদ্ধতি
Scannerদিয়ে ফাইল পড়েStringBuffer-এ জমা করুন।String.replaceAll(oldLine, newLine)দিয়ে পুরানো লাইনটি নতুন লাইন দিয়ে রিপ্লেস করুন।FileWriterদিয়ে ফাইলটি ওভাররাইট করুন।
উদাহরণ
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OverwriteLine {
public static void main(String args[]) throws IOException {
String filePath = "D://input.txt";
// ১. ফাইল পড়ে StringBuffer-এ নেওয়া
Scanner sc = new Scanner(new File(filePath));
StringBuffer buffer = new StringBuffer();
while (sc.hasNextLine()) {
buffer.append(sc.nextLine() + System.lineSeparator());
}
sc.close();
String fileContents = buffer.toString();
System.out.println("Original Contents:\n" + fileContents);
// ২. নির্দিষ্ট লাইন রিপ্লেস
String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
String newLine = "Enjoy the free content";
fileContents = fileContents.replaceAll(oldLine, newLine);
// ৩. ফাইল ওভাররাইট
FileWriter writer = new FileWriter(filePath);
writer.append(fileContents);
writer.flush();
writer.close();
System.out.println("\nNew Contents:\n" + fileContents);
}
}
আউটপুট
Original Contents: Tutorials Point originated from the idea... Simply Easy Learning! New Contents: Tutorials Point originated from the idea... Enjoy the free content
দ্রষ্টব্য:
replaceAllরেগুলার এক্সপ্রেশন নেয়। স্পেশাল ক্যারেক্টার থাকলেPattern.quote(oldLine)ব্যবহার করুন।- বড় ফাইলের জন্য মেমোরি সমস্যা হতে পারে। সেক্ষেত্রে টেম্পোরারি ফাইল ব্যবহার করে লাইন বাই লাইন প্রসেস করা ভালো।
Files.writeString()(Java 11+) বাFiles.write()(NIO.2) ব্যবহার করলে কোড সংক্ষিপ্ত হয়।