在 Eclipse PDE 视图中打开文件

Open a file in an Eclipse PDE View

我创建了一个名为 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() {
    }
}

与其使用 Scanner 阅读,我建议使用此处描述的更简洁的方法:How can I read a large text file line by line using Java?

我还建议不要重复调用 setText 并简单地附加到当前文本;相反,使用 StringBuilder 并使用 StringBuilder.

的结果简单地调用 setText

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

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() {
    }
}