0

I try to get the path to the directory my class is in. That works fine. But I want to edit this path like this. Example:

Take this path:
/C:/User/Folder1/bin/

I want to change above path to this:
C:\\User\\Folder1\\bin\\

Now, I have written this code to accomplish this:

path = StartUp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(path);
System.out.println(decodedPath);

pathArray = decodedPath.split("/");

pathLength = pathArray.length;
int x = 1;
while(x <= pathLength){
    goodPath = goodPath + pathArray[x] + "\\";
    x++;
}

System.out.println("goodPath " + goodPath);
System.out.println(decodedPath);

I thought this would accomplish it, but all output I get is:

/C:/User/Folder1/bin/
/C:/User/Folder1/bin/
5

For some reason it displays the number of elements in pathArray and skips the last two System.out.println()'s.

Does anyone know what is going on here?

ikhebgeenaccount
  • 353
  • 6
  • 20

2 Answers2

1

It is because of an array out of bound exception.

Change

while(x <= pathLength){

with

while(x < pathLength){

In Java array indexes start from zero, therefore if an array is of lenght L, then the last item in the array has the index L-1. Therefore in your case you have to loop untile x is strictly smaller than pathLength (your array's length), and not smaller or equal to that. Otherwise in the last iteration variable x takes the value of pathLength and you will access an memory location of of the bounds of your array.

An additional annotations is that you start your loop with x=1, this is right in this case only because your original string start with the character /, and then the split function create an array where the first item (index zero) is an empty string, therefore is right to skip it by starting by index one.

Anyway, I suggest you also to take a look into the regular expressions, or easier in the method replace of the class String.

WoDoSc
  • 2,598
  • 1
  • 13
  • 26
0

Use a regex like (?<!^)\\/ and drop the first character. No need manually remove every forward slash. Or do the reverse drop the first character and replace the forward slashes eg.

String path = StartUp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(path);
System.out.println(decodedPath);

Pattern compile = Pattern.compile("\\/");
Matcher matcher = compile.matcher(decodedPath.substring(1));
String replaceAll = matcher.replaceAll("\\\\\\\\");
System.out.println(replaceAll);
Dhrubajyoti Gogoi
  • 1,265
  • 10
  • 18