简体   繁体   English

在 Eclipse PDE 视图中打开文件

[英]Open a file in an Eclipse PDE View

I have created an Eclipse PDE view, called SampleView.我创建了一个名为 SampleView 的 Eclipse PDE 视图。 Currently, to programmatically display the output from my file on the view, I am consuming each line from the file, and printing to the view using a scanner.目前,为了以编程方式在视图上显示我的文件中的 output,我正在使用文件中的每一行,并使用扫描仪打印到视图。 Is this the best way to display the file data?这是显示文件数据的最佳方式吗? Or is there a better, existing function that I can use in my code to open the file in the view?或者是否有更好的现有 function 可以在我的代码中用于在视图中打开文件?

Code for SampleView: 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() {
    }
}

Instead of reading using a Scanner , I'd recommend the cleaner approach described here: How can I read a large text file line by line using Java?我建议使用此处描述的更简洁的方法,而不是使用Scanner进行阅读: 如何使用 Java 逐行读取大型文本文件?

I'd also recommend not repeatedly calling setText and simply appending on the current text;我还建议不要重复调用setText并简单地附加在当前文本上; instead, use a StringBuilder and simply call setText with the result of the StringBuilder .相反,使用StringBuilder并使用StringBuilder的结果简单地调用setText

All together, it would look something like this:总之,它看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM