hklel
hklel

Reputation: 1634

String literal is not properly closed error for backslash

Here is part of my code

OutputStream os;
    if (isWin){
        os = new FileOutputStream(folder + "\" + destinationFile);
    }
    else{
        os = new FileOutputStream(folder + "/" + destinationFile);
    }

I got the "string literal is not properly closed by double quote error" at the backslash line. if I remove the backslash or change it to forward slash, the error will disappear.

How can I fix this? Thanks.

Upvotes: 1

Views: 6764

Answers (8)

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

Multiple ways to solve:

    // Fix the '\'
    if (isWin) {
        os = new FileOutputStream(folder + "\\" + destinationFile);
    } else {
        os = new FileOutputStream(folder + "/" + destinationFile);
    }
    // Avoid using path separator
    os = new FileOutputStream(new File(folder, destinationFile));
    // OS agnostic
    os = new FileOutputStream(folder + File.separator + destinationFile);

Upvotes: 2

xxxvodnikxxx
xxxvodnikxxx

Reputation: 1277

I guess you need to put \ and / into this string. Problem is there - while you use \" in string, that will print " character, you need to "escape" character which you need- in this case you need to escape \, so you have the solution there

 os = new FileOutputStream(folder + "\" + destinationFile);

Btw try it paste into system.out and you will see :)

  • " \n " - new line
  • " \t " - tab
  • " " " error
  • " \" " - print "
  • " ' " - print '
  • " \ " - print \

:o)

Upvotes: 0

Nitesh Virani
Nitesh Virani

Reputation: 1712

You should use File.separator instead of \ and /

Upvotes: 2

Fran Montero
Fran Montero

Reputation: 1680

Is better to use File api for separators, so you have not to check what OS it is:

os = new FileOutputStream(folder + File.separatorChar + destinationFile);

Upvotes: 7

gandra404
gandra404

Reputation: 6071

To avoid slash and backslash:

OutputStream os = new FileOutputStream(new File(new File(folder ), destinationFile));

Upvotes: -1

insidesin
insidesin

Reputation: 743

\ is a symbol that is part of the compilation process (has many uses in Java) and hence must be escaped if seeking it's literal value. Coincidentally, \ is also the escape sequence character.

The final solution to use a real \ (backslash) in your code is to escape it, i.e. "\\" will output \.

os = new FileOutputStream(folder + "\\" + destinationFile);

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You need to escape \ as \\.

os = new FileOutputStream(folder + "\\" + destinationFile);

Upvotes: 0

enrico.bacis
enrico.bacis

Reputation: 31484

You should use:

"\\"

instead of:

"\"

in:

os = new FileOutputStream(folder + "\" + destinationFile);

Otherwise you are backslashing the " character.

Upvotes: 3

Related Questions