java - java swing two buttons communication
问题描述
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!
推荐阅读
- android - Android Things,如何捕获进程终止
- c++ - 非平凡可复制类型的 C++ 值表示
- sql - 如何在 bigquery 窗口中查找分类异常值/噪声行
- python - pdoc3-ValueError:找不到文件或模块
- python - 如何从字符串创建图像?
- python - Django Rest Framework 嵌套可写字段 mixins drf_writable_nested
- python - 获取所采用的路径,直到 python 中的一行
- r - 在 r data.table 中添加列
- javascript - 在javascript中合并动态对象数组
- jenkins - 满足条件时对整个管道使用特殊代理