I study Java from scratch, there is a question.

Why does this code, which should create an empty text document on the desktop, when trying to compile, gives an error?

package filecreator; import java.io.File; import java.io.IOException; public class FileCreator { public static void main(String[] args) { String fileName = "My File.txt"; String filePath = "/Users/Donrumata/Desktop/"; File myFile = new File(filePath + "/" + fileName); try { myFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } 

Closed due to the fact that off-topic participants zRrr , user194374, aleksandr barakin , D-side , Streletz 21 Jun '16 at 9:17 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - Community spirit, aleksandr barakin, D-side, Streletz
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 3
    If you format the code, it immediately becomes clear that there is not enough curly braces. Format the code! - Nick Volynkin

1 answer 1

If you give all the code in a class, then at the end there is a semicolon and a closing brace after it.


While writing the answer, I saw the answer about the extra slash. Experienced to find out that their number in transit does not matter. The following code will create a file in the same directory as the code from the question:

 String fileName = "My File.txt"; String filePath = "/Users/Documents/Desktop/"; File myFile = new File(filePath + "//////" + fileName); 
  • Thank you very much! Indeed, there was a lack of a curly bracket (and where exactly was a semicolon missing? After adding a curly bracket, everything compiled.) - Rumata
  • one
    @MaximVelichkin with a comma, I got excited. Put it after the method, but it is not needed there. Happy to help! - Sanek Zhitnik pm
  • one
    Ps is more correct not to use. And File.separator (there is still a String version), I think you will find out why. - Denis Kotlyarov
  • @DenisKotlyarov did not immediately recall this. Thank you for reminding me about the method) As far as I understand, the separator is not dependent on the Windows / Linux platform - Sanek Zhitnik
  • Yes, + no need to think about the screen version /, from this readability and yes Windows / Linux - Denis Kotlyarov