কম্পিউটার

কিভাবে জাভা একটি ফাইল (.txt) ভিতরে একটি স্ট্রিং মুছে ফেলবেন?


প্রতিস্থাপন করুন() পদ্ধতিটি একটি রেগুলার এক্সপ্রেশন এবং একটি স্ট্রিংকে প্যারামিটার হিসাবে গ্রহণ করে এবং, প্রদত্ত রেগুলার এক্সপ্রেশনের সাথে বর্তমান স্ট্রিং এর বিষয়বস্তুকে মেলে, মিলের ক্ষেত্রে, স্ট্রিং এর সাথে মিলে যাওয়া উপাদানগুলিকে প্রতিস্থাপন করে৷

ReplaceAll() পদ্ধতি -

ব্যবহার করে একটি ফাইল থেকে একটি নির্দিষ্ট স্ট্রিং মুছে ফেলার জন্য
  • স্ট্রিং হিসাবে ফাইলের বিষয়বস্তু পুনরুদ্ধার করুন।

  • ReplaceAll() পদ্ধতি ব্যবহার করে একটি খালি স্ট্রিং দিয়ে প্রয়োজনীয় শব্দ প্রতিস্থাপন করুন।

  • ফাইলে ফলাফলের স্ট্রিংটি আবার লিখুন।

উদাহরণ

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StringExample {
   public static String fileToString(String filePath) throws Exception{
      String input = null;
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      return sb.toString();
   }
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://sample.txt";
      String result = fileToString(filePath);
      System.out.println("Contents of the file: "+result);
      //Replacing the word with desired one
      result = result.replaceAll("\\bTutorialspoint\\b", "");
      //Rewriting the contents of the file
      PrintWriter writer = new PrintWriter(new File(filePath));
      writer.append(result);
      writer.flush();
      System.out.println("Contents of the file after replacing the desired word:");
      System.out.println(fileToString(filePath));
   }
}

আউটপুট

Contents of the file: Hello how are you welcome to Tutorialspoint
Contents of the file after replacing the desired word:
Hello how are you welcome to

  1. জাভাতে বিদ্যমান JSON ফাইলে কীভাবে একটি JSON স্ট্রিং যুক্ত করবেন?

  2. জাভাতে Gson লাইব্রেরি ব্যবহার করে ফাইলে একটি JSON স্ট্রিং কীভাবে লিখবেন?

  3. কীভাবে জাভাতে ফাইল এবং ডিরেক্টরি মুছে ফেলবেন

  4. জাভাতে স্ট্রিংগুলি কীভাবে তুলনা করবেন