我在文件保存方面有问题,因为我搜索了它,我写得很好,除了一件事,文件没有真正创建。少了什么?
Button btnExport = new Button(composite_1, SWT.NONE);
btnExport.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileSave = new FileDialog(pmComp, SWT.SAVE);
fileSave.setFilterNames(new String[] {"CSV"});
fileSave.setFilterExtensions(new String[] {"*.csv"});
fileSave.setFilterPath("c:\\"); // Windows path
fileSave.setFileName("your_file_name.csv");
fileSave.open();
System.out.println("File Saved as: " + fileSave.getFileName());
}
});
btnExport.setBounds(246, 56, 75, 40);
btnExport.setText("Export");发布于 2018-08-27 07:36:37
来自FileDialog:
这个类的实例允许用户导航文件系统和,选择或输入一个文件名。
对话框不会自行创建文件,您必须检索选定的文件名,然后创建文件。
e.g
String name = fileSave.getFileName();
File file = new File(name);
file.createNewFile();发布于 2018-08-27 07:37:03
FileDialog只用于选择保存文件的位置。它做的是,而不是,而是实际创建或编写文件--您必须这样做。
所以
String savePath = fileSave.open();
// TODO your code to write the file to savePath发布于 2018-08-27 07:59:43
import java.io.File;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
public class Snippet {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite.setLayout(new GridLayout(1, false));
Button btnExport = new Button(composite, SWT.NONE);
btnExport.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileSave = new FileDialog(shell, SWT.SAVE);
fileSave.setFilterNames(new String[] { "CSV" });
fileSave.setFilterExtensions(new String[] { "*.csv" });
fileSave.setFilterPath("C:\\"); // Windows path
fileSave.setFileName("your_file_name.csv");
String open = fileSave.open();
File file = new File(open);
try {
file.createNewFile();
System.out.println("File Saved as: " + file.getCanonicalPath());
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnExport.setBounds(246, 56, 75, 40);
btnExport.setText("Export");
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}https://stackoverflow.com/questions/52034511
复制相似问题