In my swing application, I need to choose a file.and then compile that file in a terminal.But before compiling, I want to delete if other files are present in the directory of chosen file. I have the file path but I need the parent folder path, to check other files.
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
l.setText("File Ready");
File selectedFile = j.getSelectedFile();
path=selectedFile.getAbsolutePath();
} else
l.setText("the user cancelled the operation");
}
});
compile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
Process proc = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
StringBuilder builder = new StringBuilder();
File folder = new File(path);
for (File f : folder.listFiles()) {
if (f.getName().endsWith(".txt")) {
f.delete();
}
});
Well there is a mistake you are doing in this part
File folder = new File(path);
for (File f : folder.listFiles()) {
if (f.getName().endsWith(".txt")) {
f.delete();
The line File folder = new File(path);
will give the file reference not folder reference So if you list other files in the path, there will be nothing.
Change it to File folder = new File(path).getParentFile();
You have the parent folder. Now list and delete needed files.
Hope this helps!
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.