简体   繁体   中英

createNewFile() Throws FileNotFoundException When Given the Correct FilePath

Here is my code below:

public void playerNaming() throws IOException {
      Scanner pickName = new Scanner(System.in);
      System.out.println("What do you want your username to be?");
      String playerName = pickName.nextLine();
      userName = playerName;
      File file1 = new File("PlayerFiles\\" + playerName + ".txt");
      File file2 = new File(file1.getAbsolutePath());
      System.out.println(file2);
      file2.createNewFile();
      BufferedWriter file3 = new BufferedWriter(new FileWriter(file2));
}

On line file2.createNewFile(); It throws

java.io.FileNotFoundException: (Insert correct FilePath here) The system cannot find the path specified

What is wrong? According to all the articles and other stackoverflow questions I have read, this should work.

Check your file path:

public static void main(String args[]) 
    { 
  
        try { 
  
            // Get the file 
            File f = new File("F:\\program1.txt"); 
  
            // Create new file 
            // if it does not exist 
            if (f.createNewFile()) 
                System.out.println("File created"); 
            else
                System.out.println("File already exists"); 
        } 
        catch (Exception e) { 
            System.err.println(e); 
        } 

Note: The file “F:\program.txt” is a existing file in F: Directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM