在Eclipse PDE视图中打开文件

时间:2020-07-27 22:05:57

标签: java eclipse eclipse-plugin pde

我已经创建了一个称为SampleView的Eclipse PDE视图。当前,要以编程方式在视图中显示我文件的输出,我正在使用文件中的每一行,并使用扫描仪打印到视图。 这是显示文件数据的最佳方法吗?还是在我的代码中可以使用更好的现有功能在视图中打开文件?

SampleView的代码

public class SampleView extends ViewPart {

    /**
     * The ID of the view as specified by the extension.
     */
    public static final String ID = "asher.views.id.SampleView";

    @Inject IWorkbench workbench;


     

    @Override
    public void createPartControl(Composite parent) {
        
        Text text = new Text(parent, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
        
         File file = new File("/Users/user/Desktop/untitled.json");
         Scanner sc;
        
        try {
            sc = new Scanner(file);
            while (sc.hasNextLine()) 
                  text.setText(text.getText()+"\n"+sc.nextLine()); 
            sc.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void setFocus() {
    }
}

1 个答案:

答案 0 :(得分:1)

我建议您使用此处介绍的更简洁的方法,而不是使用ScannerHow can I read a large text file line by line using Java?

我还建议不要重复调用setText并只是在当前文本上附加;而是使用StringBuilder并只需将setText的结果调用StringBuilder

总的来说,看起来像这样:

public class SampleView extends ViewPart {

    /**
     * The ID of the view as specified by the extension.
     */
    public static final String ID = "asher.views.id.SampleView";

    @Inject IWorkbench workbench;  

    @Override
    public void createPartControl(Composite parent) {
        Text text = new Text(parent, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
        StringBuilder builder = new StringBuilder("");
        try (Stream<String> stream = Files.lines(Paths.get("/Users/user/Desktop/untitled.json"));) {
            stream.forEach(line -> builder.append(line).append("\n"));
            text.setText(builder.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void setFocus() {
    }
}