在Eclipse PDE视图中打开文件

i2loujxw  于 2023-06-22  发布在  Eclipse
关注(0)|答案(1)|浏览(172)

我已经创建了一个Eclipse PDE视图,称为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() {
    }
}
lx0bsm1f

lx0bsm1f1#

与其使用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() {
    }
}

相关问题