1

I am writing a server program and a client program. I named the server code file server.java. The client runs from a different machine. One of the things the client can do is upload files to the server. I want the server to store the uploaded files in a folder which resides in the same directory as the server.java program file. So I used the following code:

String server_files_location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

This did work. However I have to declare this variable separately in all the different classes I am writing. I want to make this a global string variable so that I dont have to declare this every time I add a new class or method.

So at the beginning of the program I tried:

public static String server_files_location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

This gives me an error saying Cannot make a static reference to the non-static method getClass() from the type Object.

How else can I get this variable to be accessible globally?

2 Answers 2

3

Use a class literal from the class you're declaring the variable in.

public static String server_files_location =
    YourClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

Consider making the variable final if it's a constant and won't ever change. Additionally, the normal Java variable naming convention would say to name the variable in camel case, e.g. serverFilesLocation, or if it's a constant, in ALL CAPS, e.g. SERVER_FILES_LOCATION.

Sign up to request clarification or add additional context in comments.

1 Comment

How would you declare DataInputStream or DataOutputStreamor BufferedReader globally?
0

delete static in your declaration of the variable. All the instances will be able to access one instance's copy of it if both the variable and the instance in question are public.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.