Javaでファイル(.txt)内の文字列を削除するにはどうすればよいですか?
replaceAll() メソッドは、正規表現と文字列をパラメータとして受け入れ、現在の文字列の内容を指定された正規表現と照合します。一致する場合は、一致した要素を文字列に置き換えます。
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
-
Javaで既存のJSONファイルにJSON文字列を追加するにはどうすればよいですか?
Gson はJava用のjsonライブラリであり、JSONの生成に使用できます。最初のステップでは、JSONファイルを読み取ってJavaオブジェクトに解析し、型キャストする必要があります。 JSonObjectへのJavaオブジェクト JsonArrayに解析します 。次に、このJSON配列を繰り返して、 JSONElementを出力します。 。 JsonWriterを作成できます JSONでエンコードされた値を一度に1つのトークンでストリームに書き込むクラス。最後に、新しいJSON文字列を既存のjsonファイルに書き込むことができます。 例 import java.io.*; im
-
JavaのGsonライブラリを使用してJSON文字列をファイルに書き込む方法は?
Gsonは、JavaオブジェクトをJSON表現に変換するために使用できるライブラリです。 。使用する主なクラスはGson new Gson()を呼び出すことで作成できます およびGsonBuilder クラスを使用してGsonインスタンスを作成できます。 JSON文字列をファイルに書き込む toJson()を使用する Gsonの方法 以下の例のクラス 例 import java.io.*; import com.google.gson.*; public class JSONToFileTest { public static void main(String[