Dynamic Path to a File

Answered

I have a binary (testBin) in `resources` folder.
In my code, when I statically get access to it (`/Users/usernameee/MyProj/src/main/resources/testBin`), it can find the binary.
But when I want to have the dynamic path to it, by dynamic I mean as it's a plugin and other people are going to install it, I need a dynamic path to the binary, so I tried: `this.javaClass.getResource("testBin")?.toString()` but I get this error:
Error: Error: Cannot find module '/Users/usernameee/Myproj/ASWorkspace/SampleAppToTryPluginInIt/app/src/main/res/drawable/jar:file:/Users/usernameee/Projectz/Myproj/build/idea-sandbox/plugins/Myproj/lib/instrumented-MyProj-1.0.1.jar!/testBin'

How can I get the path to the file under resources that work for all the machines and users who install my plugin?
 

0
4 comments

Hi,

Try using com.intellij.util.ResourceUtil and pass plugin class loader, e.g. YourPluginClass.class.getClassLoader():

new String(ResourceUtil.getResourceAsBytes("testBin", YourPluginClass.class.getClassLoader()))
0

It returns the content of the file; I want the path.

it's an application written in nodejs, and testBin content:

#!/usr/bin/env node

require('./dist/index').run();


___
and then I do this:

runNodeScript(ThePathFromAbove, psiFile.virtualFile)

 

and then:

private fun runNodeScript(ThePathFromAbove: String, file: VirtualFile) {
        val fullPath = file.path
        try {
            // Build the command to execute
            val command = arrayOf("node", ThePathFromAbove, fullPath)
            val workingDirectory = file.parent?.path
            val processBuilder = ProcessBuilder(*command)
            
            if (workingDirectory != null) {
                processBuilder.directory(File(workingDirectory))
            }

            // Start the process
            val process = processBuilder.start()
            
            val errorReader = BufferedReader(InputStreamReader(process.errorStream))
            var errorLine: String?
            
            while (errorReader.readLine().also { errorLine = it } != null) {
                println("Error: $errorLine")
            }

            val exitCode = process.waitFor()
            println("Script executed with exit code: $exitCode")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
0

I even used `ResourceUtil.getResource(MyRightClickAction::class.java.classLoader, ".", "testBin").path` but still returns `file:/Users/usernameee/Projectz/Myproj/build/idea-sandbox/plugins/Myproj/lib/instrumented-MyProj-1.0.1.jar!/testBin` and the same error.

0

This did the trick: this::class.java.classLoader.getResource("name-of-file-in-resources-folder")

1

Please sign in to leave a comment.