Java में फ़ाइल में एक विशिष्ट लाइन को संशोधित करने के लिए: पूरी फ़ाइल पढ़ें, स्ट्रिंग में लक्ष्य लाइन बदलें, पूरी फ़ाइल वापस लिखें।
प्रक्रिया
Scannerके साथ फ़ाइल कोStringBuilderमें पढ़ेंString.replaceAll(oldLine, newLine)का उपयोग करेंFileWriterके साथ वापस लिखें
उदाहरण
import java.io.*;
import java.util.Scanner;
public class OverwriteLine {
public static void main(String args[]) throws IOException {
String filePath = "D://input.txt";
// फ़ाइल पढ़ें
StringBuilder buffer = new StringBuilder();
try (Scanner sc = new Scanner(new File(filePath))) {
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()).append(System.lineSeparator());
}
}
String content = buffer.toString();
System.out.println("Original:\n" + content);
// लाइन बदलें
String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
String newLine = "Enjoy the free content";
content = content.replaceAll(oldLine, newLine);
// वापस लिखें
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(content);
}
System.out.println("Updated:\n" + content);
}
}आउटपुट
Original: ... Simply Easy Learning! Updated: ... Enjoy the free content
नोट्स
replaceAllरेगेक्स का उपयोग करता है; विशेष वर्णों को एस्केप करें याreplace(सादे पाठ) का उपयोग करें।- बड़ी फ़ाइलों के लिए, लाइन-बाय-लाइन प्रोसेसिंग के साथ अस्थायी फ़ाइल का उपयोग करें।
- हमेशा try-with-resources का उपयोग करें।