1

I have code that can create file in D disk in my Computer an can write some information in this file.Here is source

File file = new File("D:\\" + filename);
FileWriter writer = new FileWriter(file, true); 
writer.write(builder.toString());
writer.close();
System.out.println("done!");
statusText.setText("Information successfully saved!");
statusText.setForeground(Color.BLACK);

This code working correct but when i try to change file directory like this i have exception

File file = new File("D:\\testFolder\\" + filename);

Here is a exception

IOException: D:\testFolder\2017-08-11.csv (The system cannot find the path specified)

What am i doing wrong or how i can solve my problem?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Beka
  • 143
  • 1
  • 3
  • 11

2 Answers2

2

you can not do that if that folder doesnt exist... you will just get an java.io.FileNotFoundException

create the folder firts

File dir = new File("C:\\" + "__folder");
dir.mkdir(); 

or

dir.mkdirs(); 

depending on how deep the parent/child folders go

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Thanks,but i know how to check if file exist.But I would check like this.If directory exist (D:testfolder for example) create some file inside this directory ,else create new folder and then create new file @ΦXocę 웃 Пepeúpa ツ – Beka Aug 11 '17 at 10:10
-1

Try Creating Directory first:

            String filename = "myfile";
            File file= null;

//          Check if directory exists
            File directory = new File("D:\\testFolder\\");
            if (directory.exists() && directory.isDirectory()) {
                //create your file
                file =  new File(directory +"\\"+ filename); 
            } else {
                // Create directory
                directory = new File("C:\\testFolder\\");

                if(directory.mkdir()) {
                    System.out.println("Directory Created");
                    file =  new File(directory +"\\"+ filename); 

                } else {
                    System.out.println("Directory is not created");
                }

                // Create file
            }

            FileWriter writer = null;
            try {
                writer = new FileWriter(file, true);
                writer.write(builder.toString());
                writer.close();
                System.out.println("done!");
                statusText.setText("Information successfully saved!");
                statusText.setForeground(Color.BLACK);
            } catch (IOException e) {
                e.printStackTrace();
            }
mohit sharma
  • 1,050
  • 10
  • 20