IntelliJ IDEA插件开发:如何存储FileChooser选中的文件路径
你调用的FileChooser.chooseFile()方法会返回选中的VirtualFile可空实例,你只需接收该返回值,调用其path属性即可拿到文件路径,再根据你的使用场景选择存储方式即可。
基础修改后的代码示例:
val fileChooser = FileChooserDescriptor( true, false, false, false, false, false ).apply { title = "Choose the files" description = "Choose the files" } // 接收选中的文件对象 val selectedFile = FileChooser.chooseFile(fileChooser, e.project, null) // 非空判断后获取路径 selectedFile?.let { file -> val filePath = file.path // 此处按需求选择存储路径的方式 }
不同存储场景实现
1. 临时存储(插件运行时有效,IDEA重启后丢失)
直接在当前类定义成员变量存储即可:
class MyCustomAction : AnAction() { // 成员变量存储路径 private var selectedFilePath: String? = null override fun actionPerformed(e: AnActionEvent) { // 文件选择逻辑省略 selectedFile?.let { selectedFilePath = it.path // 后续业务逻辑直接读取selectedFilePath即可 } } }
2. 持久化存储(IDEA重启后路径依然保留)
如果需要长期存储路径,使用IDEA插件提供的PersistentStateComponent持久化组件实现:
- 先定义持久化状态类:
@State( name = "MyPluginConfig", storages = [Storage(value = "my-plugin-config.xml")] ) class MyPluginPersistentState : PersistentStateComponent<MyPluginPersistentState.State> { data class State(var selectedFilePath: String? = null) private var currentState = State() override fun getState(): State = currentState override fun loadState(state: State) { currentState = state } companion object { fun getInstance(): MyPluginPersistentState = ServiceManager.getService(MyPluginPersistentState::class.java) } }
- 存储路径时调用:
MyPluginPersistentState.getInstance().state.selectedFilePath = filePath
- 读取路径时直接读取对应属性即可:
val savedPath = MyPluginPersistentState.getInstance().state.selectedFilePath
内容的提问来源于stack exchange,提问作者Meg
相关产品推荐
相关产品推荐

