简体   繁体   中英

Using environment variables in a Java File Path

I am writing a Java program to convert an XLS file to a CSV file for some Python parsers to act on them.

Everyday on my desktop (I'm using Ubuntu btw) I have a folder called "DFiles" inside which there is another folder called "20140705" (this folder is dynamicalle generated, tomorrow some other program deletes this folder and makes a new folder called 20140706 in its place). Inside this folder there is an xls file whose name is always "data.xls". I already have the code to convert it to CSV.

So here's my problem. Tomorrow my code my run on someone else's desktop(which is also Ubuntu). So when giving the path

input_document = new FileInputStream(new File("/home/local/TNA/srini/Desktop/DFiles/20140705/data.xls"+)); 

This unfortunately will work only today and only on my computer.

Ideally, I would like to do some thing like set the path to "$HOME/Desktop/Dfiles/2*/data.xls" as the file path. So how can I use bash env variables and wild cards in a file path in java?

You can get the value of an environment variable using System.getenv(...) :

String homeDir = System.getenv("HOME");
String directory = homeDir + "/Desktop/DFiles/...";

Wildcards: That will not work. You can use listFiles() to list the files and directories inside a certain directory.

File dir = new File(homeDir + "/Desktop/DFiles";
for (File f : dir.listFiles()) {
    if (f.isDirectory()) {
        System.out.println("Found subdirectory: " + f.getName());
    } else {
        System.out.println("Found file: " + f.getName());
    }
}

You can write some code that recursively goes into the subdirectories and picks up any file of which the name ends with '.xls'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM