1

I want to control in which folder my file is.

I work with a certain folder structure:

  1. Main folder
  2. processing subfolder
  3. processed subfolder

To write my unit tests I want to put the test folder in the target which gives following folder structures

target\test-folder\

This is the main folder

target\test-folder\processing\

This is the subfolder processing

target\test-folder\processed

This is the subfolder processed

I want to print out in which folder a certain file is, what I wanted to do is the following:

String[] directories = PATH.split("\"");
System.out.println(directories[directories.length - 2]);

When I debug I see that my array directories only contain 1 item, with the whole path, so my split is probably wrong.

What should I put as split value?

3
  • 3
    Probably ought to be using the types Path or File. Commented Apr 8, 2015 at 12:13
  • I agree with @Raedwald. You should not do String manipulation but rather use the File object, figure out the parent, and so on so forth Commented Apr 8, 2015 at 12:16
  • Ok seems a good solution. Commented Apr 8, 2015 at 12:20

2 Answers 2

2

First of all you are using backslash as an escape character instead of what you want. You should split with argument "\\", HOWEVER I'd advise you to use FileSystems.getDefault().getSeparator() instead of backslash, so it might run on linux or any other system (perhaps even in some magic land where people use ^ as path separator). Unfortunately in Windows it returns \ (which is escape character) so you have to quote it using Pattern.quote(String)

The code should look like this:

String[] directories = PATH.split(Pattern.quote(FileSystems.getDefault().getSeparator()));
Sign up to request clarification or add additional context in comments.

3 Comments

This throws: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \
Edited my answer, please try again
and it works. Thanks for the effort, you deserve the credits!
1

Instead of splitting strings you should use the built in classes, such as Path. Contrived example to access the individual elements of the path:

Path p = Paths.get("target/test-folder/processed");
for (Path element : p) System.out.println(element); //loop over all elements
System.out.println(p.getName(2)); //access a specific element

which outputs:

target
test-folder
processed
processed

1 Comment

One little detail, this needs to be dynamical. So it needs to be used in every folder on the file system with the 2 subfolders. But thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.