您可以将路径放在属性文件中,并使用Java中的Properties
类来读取它。 示例代码:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
}catch(IOException e){
//handle exception
}
更多details-- 你必须创建一个新的属性文件,它仅仅是一个.properties扩展名的文件。我们称之为sample.properties。您可以放置值,这些值是键值对。这是你将如何把值有:
dirpath = /home/dextr/Documents/docs/
fileName = puzzle.txt
你,你将不得不放置特性在应用程序的根文件或者你将不得不提供以读它的相对路径。 然后,使用类似以下代码的代码读取properties
对象中的值。根据您需要的值,您使用适当的密钥。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SoSample {
public static void main(String[] args) {
Properties properties = new Properties();
InputStream input = null;
try {
input = new FileInputStream("sample.properties");
properties.load(input);
String dirPath = (String)properties.get("dirpath");
System.out.println(dirPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
是否有一种特定的方式来指定属性文件中的路径?目前有它在“路径= C:\\文件夹” – gio10245
这很好。你试过了吗? –
是的,我不知道该怎么改变目录中的代码 - 文件file1 =新文件(dir,filePath);因为dir是硬编码的。加载属性文件中的代码似乎很好,但我确定如何在我的代码中使用它 – gio10245