I needed to create a file in a folder, but no matter what methods I tried, they write an error. They all sound like this:

(The system cannot find the specified path)

so, in my project there is a folder "Save" in it you need to create a file

I tried this option:

String filePath = new File("Save").getAbsolutePath(); FileWriter fstream = new FileWriter(filePath + "\\test.txt"); BufferedWriter out = new BufferedWriter(fstream); 

and here it is:

 String filePath = new File("Save").getAbsolutePath(); File file = new File(filePath + "\\test.txt"); file.createNewFile(); 

all to no purpose

On the Internet there is nothing sensible found. Thank you in advance.

  • 3
    Did you check filePath ? Does he point to the correct folder? - default locale

2 answers 2

Perhaps the "Save" folder should have been initialized as an object of the File class, declared as a directory and then created a file in it.

 public static void main(String[] args) { File filePath = new File("Save"); filePath.mkdir(); File file = new File(filePath + "\\test.txt"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } 
  • thanks, everything earned - morp morpovich
 // создать все директории если их вдруг ещё нет path/to/files Path dir = Files.createDirectories(Paths.get("path", "to", "files")); // или так Files.createDirectories(Paths.get("path/to/files")); // создать собственно файл path/to/files/filename.ext OutputStream out = Files.newOutputStream(dir.resolve("filename.ext"));