Avatar ·

How to get the current working directory in Java?

Hello everyone! I'm just starting to learn Java and ran into a problem: I need to know which folder my program is in to read a configuration file. Let's say I have this code:

\n\n
import java.io.File;\n\npublic class Main {\n    public static void main(String[] args) {\n        File config = new File("config.txt");\n        if (config.exists()) {\n            System.out.println("File found!");\n        } else {\n            System.out.println("File not found. Where am I?");\n        }\n    }\n}\n
\n\n

The problem is that this code only works if I run the program from the same folder where config.txt is located. If I run it from another directory, the file is not found. How can I get the absolute path to the current working folder in Java so I can build