【发布时间】:2012-06-06 02:50:19
【问题描述】:
我正在为我们的应用程序开发一个图形安装程序。由于没有可用的安装程序生成器满足要求和限制,我正在从头开始构建它。
安装程序应该在多个操作系统上运行,因此路径处理需要与操作系统无关。为此,我编写了以下小实用程序:
public class Path {
private Path() {
}
public static String join(String... pathElements) {
return ListEnhancer.wrap(Arrays.asList(pathElements)).
mkString(File.separator);
}
public static String concatOsSpecific(String path, String element) {
return path + File.separator + element;
}
public static String concatOsAgnostic(String path, String element) {
return path + "/" + element;
}
public static String makeOsAgnostic(String path) {
return path.replace(File.separator, "/");
}
public static String makeOsSpecific(String path) {
return new File(path).getAbsolutePath();
}
public static String fileName(String path) {
return new File(path).getName();
}
}
现在我的代码在很多地方都充斥着Path.*Agnostic 和Path.*Specific 调用。很明显,这很容易出错,而且根本不透明。
我应该采取什么方法来使路径处理透明且不易出错?是否存在已经解决此问题的任何实用程序/库?任何帮助将不胜感激。
编辑:
为了举例说明我的意思,这是我不久前写的一些代码。 (题外话:原谅冗长的方法。代码处于初始阶段,很快将进行一些重度重构。)
一些上下文:ApplicationContext 是一个存储安装数据的对象。这包括多个路径,例如installationRootDirectory、installationDirectory 等。这些路径的默认值是在创建安装程序时指定的,因此始终以与操作系统无关的格式存储。
@Override
protected void initializeComponents() {
super.initializeComponents();
choosePathLabel = new JLabel("Please select the installation path:");
final ApplicationContext c = installer.getAppContext();
pathTextField = new JTextField(
Path.makeOsSpecific(c.getInstallationDirectory()));
browseButton = new JButton("Browse",
new ImageIcon("resources/images/browse.png"));
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int choice = fileChooser.showOpenDialog(installer);
String selectedInstallationRootDir = fileChooser.getSelectedFile().
getPath();
if (choice == JFileChooser.APPROVE_OPTION) {
c.setInstallationRootDirectory(
Path.makeOsAgnostic(selectedInstallationRootDir));
pathTextField.setText(Path.makeOsSpecific(c.getInstallationDirectory()));
}
}
});
}
【问题讨论】:
-
用
/分隔路径在Windows 上运行得非常好。除此之外,您为什么还需要不可知论版本? -
@Mat,我知道。以下是一些情况: 1.
File#getAbsolutePath返回一个带有操作系统特定分隔符的字符串。 2.System.getProperty(<something that returns a path>)返回一个带有操作系统特定分隔符的字符串。 3. 我需要读取和写入某些安装面板中的文本框,并且在呈现给用户时,路径需要采用特定于操作系统的格式。 -
当然。那么 *Agnostic 的用途是什么?
-
@Mat,让我在我的问题中添加一个代码示例。
-
是否需要显示相同的分隔符? (例如,对所有操作系统使用 ``)。如果没有,只需使用一个小实用程序来确定不支持的分隔符,并在写入 FS 之前将其替换。这样你就不会强迫用户做任何“特定于操作系统”的事情
标签: java cross-platform file-handling