2008年7月31日木曜日

String.replaceAllの問題

JavaにreplaceAllを使って、パス変換にする時、
エラー(StringIndexOutOfBoundsException)が発生したことがあるでしょう。
それでは、解明しよう*П*
("\":円マーク、"/":スラッシュ)

仕様条件:
パス①からパス②に変換
①=http://www.google.co.jp/iGoogle/html/sample.htm
②=D:\MyGoogle\iGoogle\html\sample.htm

解決案:
StringタイプのreplaceAll(A,B)を使います。

説明:
◆変換元の定義:
String A="http://www.google.co.jp/iGoogle/html/sample.htm";
◆変換先の定義:
変換先のパスはどう定義しますか?下記のようにすればどう?
String B="D:\MyGoogle\iGoogle\html\sample.htm";
結果:×
原因:
文字列の"\"に変換する場合、少なくとも二つの円マーク(即ち:"\\")が必要となる
このうち、一つはエスケープコードといって特殊なコードです。なければ、
「StringIndexOutOfBoundsException」というエラーが出てくる。
上記Bの正しい定義:String B="D:\\MyGoogle\\iGoogle\\html\\sample.htm";
◆特殊場合:
実際に上記の仕様条件を実現するため、必ず一つの円マークが定義される限りないです。
いくつの円マークが必要ということは、ソース内部の処理回数に関係があります。
例:
String B="D:\\\\MyGoogle\\\\iGoogle\\\\html\\\\sample.htm";

public void changePath(String A,String B){
String tmpA=null;
String tmpB=null;

tmpA=A;
tmpB=B;//ここのtmpB:"D:\\MyGoogle\\iGoogle\\html\\sample.htm";

//同じフォルダに新しいファイルを作る
int index=tmpB.indexof("sample.htm");
String newFilePath=tmpB.substring(0,index)+"newsample.htm";
//ここのnewFilePath:"D:\\MyGoogle\\iGoogle\\html\\sample.htm";

tmpA=tmpA.replaceAll(tmpA, newFilePath);
//ここのtmpA:"D:\MyGoogle\iGoogle\html\sample.htm";
}

もし変数Bは、下記のように定義されたら、
String B="D:\\MyGoogle\\iGoogle\\html\\sample.htm";
「tmpA=tmpA.replaceAll(tmpA, newFilePath);」にいくと、
処理後のtmpA:"D:MyGoogleiGooglehtmlsample.htm";になってしまった!!!!!
なんと円マーク(\)はなくなった。
この時、tmpAに対して、他のパス処理があれば、タイトルのエラーが発生する。

::終わり:)

0 件のコメント: