0

I have created an Eclipse PDE view, called SampleView. 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. 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?

Code for 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() {
    }
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
Katya
  • 83
  • 7

1 Answers1

1

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?

I'd also recommend not repeatedly calling setText and simply appending on the current text; instead, use a StringBuilder and simply call setText with the result of the StringBuilder.

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() {
    }
}
ajc2000
  • 651
  • 5
  • 20
  • `Files.lines` returns a stream which must be closed (unlike most streams) so it should be in a 'try-with-resources'. Your current code leaves the file open. – greg-449 Jul 28 '20 at 06:50
  • Thanks @greg-449! It even points that out on the post I had linked but I glossed over it. – ajc2000 Jul 28 '20 at 14:07