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