简体   繁体   English

在Java文件路径中使用环境变量

[英]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. 我正在编写一个Java程序,将XLS文件转换为CSV文件,以便某些Python解析器对其执行操作。

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). 每天在桌面上(我使用Ubuntu btw),我都有一个名为“ DFiles”的文件夹,其中还有一个名为“ 20140705”的文件夹(此文件夹是动态生成的,明天其他程序会删除此文件夹并创建一个名为20140706)。 Inside this folder there is an xls file whose name is always "data.xls". 在此文件夹中,有一个xls文件,其名称始终为“ data.xls”。 I already have the code to convert it to CSV. 我已经有将其转换为CSV的代码。

So here's my problem. 所以这是我的问题。 Tomorrow my code my run on someone else's desktop(which is also Ubuntu). 明天我的代码将在其他人的桌面(也就是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. 理想情况下,我想做一些事情,例如将路径设置为“ $ HOME / Desktop / Dfiles / 2 * / data.xls”作为文件路径。 So how can I use bash env variables and wild cards in a file path in java? 那么,如何在Java的文件路径中使用bash env变量和通配符?

You can get the value of an environment variable using System.getenv(...) : 您可以使用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. 您可以使用listFiles()列出特定目录中的文件和目录。

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'. 您可以编写一些递归进入子目录的代码,并选择名称以'.xls'结尾的任何文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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