Java FileDialog浏览和读取文件

时间:2018-08-26 10:06:58

标签: java user-interface swt

我有一个使用FileDialog浏览文件的按钮。我需要从选择的文件中读取所有行,我已经尝试了很多方法,但是对我无济于事:(我有另一个按钮,当我按下它时,它将读取文件并打印。

        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);

            }
        }
    });

1 个答案:

答案 0 :(得分:1)

查看示例代码:

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
            });
        }
    });