Search code examples
javanetbeans-8filechooser

Java write to file and save it by fileChooser


I am new to java and moving my codes since last two years from VB to java using netbeans 8 . Now i want to write loop acumalted data to file and last to save produced file to specific place using FlieChooser below is my code but i can't see any file in My Desktop when I wrote name in doilog and press enter :

public void   SaveToFile() throws IOException {
 try (Writer writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("test.txt"), "utf-8"))) {
     int i=0;
     String Data[]=new String[10];
   while( i<10 ){
 writer.write("Student No :" + i);
  Data[i]= "Student No :" + i;
  ++i;
    }



   }

        int userSelection = db.showSaveDialog(this);
     if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = db.getCurrentDirectory();
                    String path = fileToSave.getAbsolutePath();
                    path = path.replace("\\", File.separator);
                    System.out.println("Save as file: " + path);

    }
    }

Solution

  • I see a couple problems with this. One, none of the code you're displaying here shows a call to any ".Save()" or copy or move method after choosing the directory. Two, the File object is pointing at a directory, not a file name. Three, your initial Writer object is probably writing test.txt to the directory your .class or .jar file lives in while it's running.

    You need to figure out the directory and file name you want to use BEFORE you start writing to the disk.

    UPDATE

    public void   SaveToFile() throws IOException {
        int userSelection = db.showSaveDialog(this);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = db.getCurrentDirectory();
            String path = fileToSave.getAbsolutePath() + File.separator + "test.txt";
    
            try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                      new FileOutputStream(path), "utf-8"))) {
                int i=0;
                //String Data[]=new String[10];
                while( i<10 ){
                    writer.write("Student No :" + i);
                    //Data[i]= "Student No :" + i; // Not sure why Data[] exists?
                    ++i;
                }
            }
    
            System.out.println("Save as file: " + path);
        }
    }
    

    I think this is approximate to what you will need. I don't have a java compiler at the moment, so I can't say for sure if that's all good syntax. But there are plenty of Java tutorials online.