I am a newbie to Java. I am trying to dynamically choose the file location to save the outcome of my project (to be initiated at the very start of my project). I worked around with a few FileDialog examples, but each one of them allows me to choose a file and not a folder.
Can anyone please help me with an example (or) link to one for the same?
The path for a file can be obtained using the method java. io. File. getPath().
We can use its move(Path source, Path target, CopyOption… options) method to move a directory. This method takes the directory path to be moved, the path to the target directory, and an optional parameter to specify how the move is performed.
You can check the File Documentation. There is no way to set default path instead you specify in in the File() constructor it self. AFAIK, there is no way to set default path.
Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();
You could try something like this (as shown here: Select a Directory with a JFileChooser):
import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; public class DemoJFileChooser extends JPanel implements ActionListener { JButton go; JFileChooser chooser; String choosertitle; public DemoJFileChooser() { go = new JButton("Do it"); go.addActionListener(this); add(go); } public void actionPerformed(ActionEvent e) { chooser = new JFileChooser(); chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle(choosertitle); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // // disable the "All files" option. // chooser.setAcceptAllFileFilterUsed(false); // if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); } else { System.out.println("No Selection "); } } public Dimension getPreferredSize(){ return new Dimension(200, 200); } public static void main(String s[]) { JFrame frame = new JFrame(""); DemoJFileChooser panel = new DemoJFileChooser(); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); frame.getContentPane().add(panel,"Center"); frame.setSize(panel.getPreferredSize()); frame.setVisible(true); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With