【问题标题】:Open a file in an Eclipse PDE View在 Eclipse PDE 视图中打开文件
【发布时间】:2020-07-27 22:05:57
【问题描述】:

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

【问题讨论】:

    标签: java eclipse eclipse-plugin pde


    【解决方案1】:

    我建议不要使用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() {
        }
    }
    

    【讨论】:

    • Files.lines 返回一个必须关闭的流(与大多数流不同),因此它应该位于“try-with-resources”中。您当前的代码使文件保持打开状态。
    • 谢谢@greg-449!它甚至在我链接的帖子中指出了这一点,但我掩盖了它。
    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多