Reputation: 95
I'm writing a plugin which will insert getter and setter methods into the current java file. My issue is, every time I run the plugin it seems like no change happens. However, changes do happen but only after I go into File | Synchronize do they show up in the file.
I have automatic synchronize settings turned on but this doesn't fix the issue. I've also tried looking into the intellij community edition source code to try and see what code is behind File | Synchronize but didn't manage.
public void makeGetters(AnActionEvent e, ArrayList<String> lines, String mainLine) {
Project project = e.getProject();
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
Document document = FileEditorManager.getInstance(project).getSelectedTextEditor().getDocument();
SelectionModel selectionModel = editor.getSelectionModel();
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
String fileName = virtualFile.getPath();
String method = "Error method not initiated";
String returnType = "Error return type not initiated";
for (String s : lines) {
String[] lineArray = s.split(" ");
if (s.contains(" String ")) {
returnType = "String";
}
else if (s.contains(" int ")) {
returnType = "int";
}
else if (s.contains(" double ")) {
returnType = "double";
}
else if (s.contains(" boolean ")) {
returnType = "boolean";
}
method = "\n\tpublic " + returnType + " getName () { return " + lineArray[5] + " }\n";
try {
insert(fileName, method, mainLine);
} catch (IOException exception) {
Messages.showInfoMessage("IOException in insert method", "IOException!");
} finally {
//Some line(s) of code which will synchronize the document.
}
public void insert(String fileName, String method, String mainLine) throws IOException {
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int line = lines.indexOf(" public static void main(String[] args) {") - 1;
lines.add(line,method);
Files.write(path, lines, StandardCharsets.UTF_8);
}
I would like the code to write to the file and then for the file to be synchronized at the end.
Any help or direction would be great.
Upvotes: 3
Views: 218
Reputation: 95
The following line of code fixes my problem:
VirtualFileManager.getInstance().syncRefresh()
Upvotes: 1
Reputation: 378
Looking at the documentation... perhaps you should try passing the last parameter(s) to the Files.write method, which is var args, on the last line of your insert method. Check this out:
"The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present."
Try passing SYNC in. It is a guess, but makes some sense.
Upvotes: 1