如何替换java
替换Java中的字符串
使用String类的replace方法可以替换字符串中的特定字符或子串。该方法有两个重载版本:
String replaced = originalString.replace(char oldChar, char newChar);
String replaced = originalString.replace(CharSequence target, CharSequence replacement);
示例代码:
String str = "Hello World";
String newStr = str.replace("World", "Java");
System.out.println(newStr); // 输出: Hello Java
替换Java中的正则表达式匹配项
使用String类的replaceAll方法可以基于正则表达式进行替换:

String replaced = originalString.replaceAll(String regex, String replacement);
示例代码:
String str = "a1b2c3";
String newStr = str.replaceAll("\\d", "-");
System.out.println(newStr); // 输出: a-b-c-
替换Java中的文件内容
读取文件内容后替换特定字符串并写回文件:

Path path = Paths.get("file.txt");
String content = Files.readString(path);
String newContent = content.replace("old", "new");
Files.write(path, newContent.getBytes());
替换Java集合中的元素
使用Collections类的replaceAll方法替换列表中的所有匹配项:
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
Collections.replaceAll(list, "apple", "orange");
替换Java中的环境变量
获取系统环境变量并替换值:
String path = System.getenv("PATH");
String newPath = path.replace("old_path", "new_path");
替换Java中的属性值
使用Properties类替换属性文件中的值:
Properties props = new Properties();
props.load(new FileInputStream("config.properties"));
props.setProperty("key", "newValue");
props.store(new FileOutputStream("config.properties"), null);






