0

How to edit system or user variables on Windows using Java code and JNA? I only found this question but it doesn't seem to help. Why don't the following two code snippets work?

import com.sun.jna.Library;
import com.sun.jna.Native;

public class Environment
{
    public interface WinLibC extends Library
    {
        WinLibC INSTANCE = (WinLibC) Native.loadLibrary("msvcrt",
                WinLibC.class);

        public int _putenv(String name);
    }

    public static void main(String[] args)
    {
        WinLibC.INSTANCE._putenv("MYVARIABLE=MYVALUE");
    }
}

and

import com.sun.jna.Library;
import com.sun.jna.Native;

public class Environment
{
    WinLibC clib = (WinLibC) Native.loadLibrary("msvcrt", WinLibC.class);

    public Environment()
    {
        setenv("myVariable", "myValue");
    }

    public interface WinLibC extends Library
    {
        public int _putenv(String name);
    }

    public void setenv(String variable, String value)
    {
        clib._putenv(variable + "=" + value);
    }

    public static void main(String[] args)
    {
        new Environment();
    }
}

Instead of writing the environment variable, nothing happens.

Community
  • 1
  • 1
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185

1 Answers1

0

You shouldn't need JNA to get environment variables. System.getenv() does exactly that.

On the other hand, it's generally a bad idea to set persistent environment variables in Java. It makes your program less portable (different systems have different notions of environment variable visibility/persistence), and it muddies the distinction between the JVM and the actual system's environment.

Of course, if you absolutely have to, you need to use setenv on Linux/Unix and _putenv on Windows.

yossarian
  • 1,537
  • 14
  • 21
  • It's not a bad idea when I want to make a Java program to do persistent environment variable changes and just that. I'll see if I can get it to work using your tips :) – BullyWiiPlaza Sep 19 '14 at 16:01