// 取source文件夹的绝对路径,取到为 E:\eclipse\workspace\tryBufferedReader\source
  String sourceFilePath = new File("source").getAbsolutePath();

System.out.println(sourceFilePath);
String find = "E:\\eclipse";
String targetDir = "E:\\target";
sourceFilePath.replaceFirst(find, targetDir);
System.out.println(sourceFilePath);     我想把取到的绝对路径E:\eclipse\workspace\tryBufferedReader\source的前面部分替换掉E:\eclipse\workspace\tryBufferedReader\source --->E:\target\workspace\tryBufferedReader\source但是我这样写代码,没有发生任何的替换动作,有谁知道应该怎么写吗?

解决方案 »

  1.   

    sourceFilePath = sourceFilePath.replaceFirst(find, targetDir);楼主要知道字符串一旦生成,它的值是不会变的。所以你必须将替换后生成的新字符串手动赋值给 sourceFilePath。
      

  2.   

    你好,你说的确实是一个问题,但是不是我现在讨论的问题
    sourceFilePath = sourceFilePath.replaceFirst(find, targetDir);我觉得replaceFirst这个函数根本没有发生作用,通过我定义的那个find似乎找不到匹配的字符串。我想是我的find变量定义错了,关于那个\应该要做一些处理的吧
      

  3.   

    除此之外,两个参数都要是正则表达式。
    String sourceFilePath = "E:\\eclipse\\123";
    System.out.println(sourceFilePath);
    String find = "E:\\\\eclipse";
    String targetDir = "E:\\\\target";
    sourceFilePath = sourceFilePath.replaceFirst(find, targetDir);
    System.out.println(sourceFilePath);
      

  4.   

    恩,这样子打四个\就可以了.
    sourceFilePath的值不应该看做正则,所以是匹配两个\\,用正则就变成了4个斜杠。
    我这样理解对吧。
    谢谢
      

  5.   

    你只要把sourceFilePath.replaceFirst(find, targetDir);重新赋值给sourceFilePath就可以了。另外你只是把eclipse换成target,盘符没换,直接String find = "eclipse"; String targetDir = "target";就好了,省得麻烦。不过3楼说的都没错。
      

  6.   

    我也遇到这个问题了。好棘手啊。
    最后想到一个办法。虽然很愚笨,但是只能先暂时解决这个问题了。
    先用split("//// ")将路径分开,然后再拼凑起来。
    很笨吧?
      

  7.   

    8楼高手,是个好办法。我遇到的问题是把一个windows下的路径,换成linux的路径。开始也是想近办法去替换,结果总是不成功,用了8楼的办法,虽然饶了点儿,但是最后能实现了功能,感谢!