Scala - write Windows file paths that contain spaces as string literals

4.3k views Asked by At

I need to make some Windows file paths that contain spaces into string literals in Scala. I have tried wrapping the entire path in double quotes AND wrapping the entire path in double quotes with each directory name that has a space with single quotes. Now it is wanting an escape character for "\Jun" in both places and I don't know why.

Here are the strings:

    val input = "R:\'Unclaimed Property'\'CT State'\2015\Jun\ct_finderlist_2015.pdf"
    val output = "R:\'Unclaimed Property'\'CT State'\2015\Jun"

Here is the latest error: enter image description here

2

There are 2 answers

2
Gábor Bakos On BEST ANSWER

The problem is with the \ character, that has to be escaped. This should work:

val input = "R:\\Unclaimed Property\\CT State\\2015\\Jun.ct_finderlist_2015.pdf"
val output = "R:\\Unclaimed Property\\CT State\\2015\\Jun"
2
JoeZhou On

A cleaner way to create string literals is to use triple quotes.

You can wrap your string directly in triple quotes without escaping special characters. And you can put multiple lines string in it. It's much easier to code and read.

For example

val input =

"""
  |R:\Unclaimed Property\CT State\2015\Jun.ct_finderlist_2015.pdf
"""

To add a variable to the string, do it like the following by adding "$variableName".

val input =

s"""
  |R:\Unclaimed Property\$variablePath\CT State\2015\Jun.ct_finderlist_2015.pdf
"""