[英]Java FileDialog browse and read from file
I've a button to browse file/s with FileDialog.我有一个按钮可以使用 FileDialog 浏览文件。 I need to read all lines from the file I've choose, I've tried a lot of things but nothing work to me :( I have another button that when I press on it, it will read the file and than print it.
我需要从我选择的文件中读取所有行,我尝试了很多东西,但对我没有任何作用:(我有另一个按钮,当我按下它时,它会读取文件而不是打印它。
Button btnBrowse = new Button(composite_2, SWT.NONE);
btnBrowse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileBrowse = new FileDialog(pmComp, SWT.MULTI);
fileBrowse.setFilterExtensions(new String[] {"*.txt"});
String filePath = fileBrowse.open();
if (filePath != null) {
StringBuffer buf = new StringBuffer();
files = fileBrowse.getFileNames();
for (int i = 0, n = files.length; i < n; i++) {
buf.append(fileBrowse.getFilterPath());
if (buf.charAt(buf.length() - 1) != File.separatorChar) {
buf.append(File.separatorChar);
}
buf.append(files[i]);
buf.append("\n");
}
for (int i = 0, n = files.length; i < n; i++) {
listViewer.add(files[i]);
}
System.out.println(buf);
}
}
});
See the sample code:查看示例代码:
Here btnBrowseFile
is button on which we need to select file这里
btnBrowseFile
是我们需要选择文件的按钮
this.btnBrowseFile.addListener(SWT.Selection, event -> {
final Shell shell = this.getShell();
final FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setText("Select valid text file");
dialog.setFilterExtensions("*.txt");
String selectedFileStr = dialog.open();
if (selectedFileStr != null && !selectedFileStr.isEmpty()) {
final Stream<String> lines = Files.lines(Paths.get(selectedFileStr), StandardCharsets.UTF_8);
List<String> readList = lines.collect(Collectors.toList());
lines.close();
readList.forEach(line -> {
System.out.println(line);
// Do your work
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.