Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Windows username in Java?

Tags:

java

windows

So what I am trying to do is let my Java find the user's name that windows is logged in with, so when I would say such a method, it would return the users name, like I use it in the User called Noah, java would return "Noah" and if I were on the user Amanda, Java would return "Amanda". How would I do this?

like image 225
Noah Cagle Avatar asked Nov 14 '13 22:11

Noah Cagle


People also ask

What is Window User ID?

Your user ID is the unique email address that was created for you to use when you sign in to Microsoft 365. A user ID may look similar to the following: [email protected].

How do I get the username of a computer in Java?

Java get windows Username. System.getProperty("user.name") - This method retrieve the username of the particular system from all the properties of Windows. On the Windows operating system or any other system user must first login to the OS to work on it. So, its mandatory to login to the system before using it.

How to get the current logged in user name in Java?

In Java program you may have to find the current logged in user to the system either to display the logged in user information in the appliation or to save this information in database. This program explains you the code to get the currently logged in user name (user which is running the Java program) and then display on the console.

How to retrieve the username of the particular system in Windows?

System.getProperty ("user.name") - This method retrieve the username of the particular system from all the properties of Windows. On the Windows operating system or any other system user must first login to the OS to work on it.

Can JavaScript access the windows username?

can someone help me please.. Welcome to TSDN. Javascript is for the client-side browser scripting. It shouldn't have anything to do with the operating system. That would be a huge security hole if Javascript could access the Windows username. It's possible to access the windows username using javascripts. but i dont know that.


3 Answers

Lookup the system property "user.name".

String username = System.getProperty("user.name");
  • System Properties
  • System.getProperty

Demonstration: Main.java

public class Main {
   public static void main(String[] args) {
      System.out.println(System.getProperty("user.name"));
   }
}

Output:

c:\dev\src\misc>javac Main.java

c:\dev\src\misc>java Main
rgettman

c:\dev\src\misc>
like image 81
rgettman Avatar answered Oct 07 '22 07:10

rgettman


Try:

String userName = System.getProperty("user.name");

or

String userName = new com.sun.security.auth.module.NTSystem().getName()
like image 20
user987339 Avatar answered Oct 07 '22 06:10

user987339


Two ways

  1. System.getProperty("user.name");

  2. System.getenv("USERNAME");

Both are good for any OS

like image 18
Evgeniy Dorofeev Avatar answered Oct 07 '22 08:10

Evgeniy Dorofeev