Java-跨平台文件路径 [英] Java - Cross-platform filepath

查看:85
本文介绍了Java-跨平台文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaFX和Gluon开发一个跨平台应用程序,该应用程序也可以在台式机和Android上运行.

I'm trying to develop a cross-platform application that works on Desktop and Android as well using JavaFX and Gluon.

在运行时,我的代码在我的资源文件夹中创建一个序列化文件.我还需要读取/写入序列化数据.

At runtime my code creates a serialized file in my resource folder. I also need to read and write serialized data from/to it.

我设法在台式机上工作,但在android上却没有.我猜因为它具有不同的文件结构. 这就是为什么我尝试动态获取文件路径的原因.

I managed to work it on desktop, but not on android. Because it have a different file structure I guess. That is why I try to get the file path dynamically.

在运行时之前创建(而不进行修改)的现有资源文件似乎在两个平台上都可以正常工作.

Existing resource files, which are created before runtime (and not modified) seems to works fine on both platform.

我尝试使用new File("src/main/resources/folder/file.ser").getAbsolutePath();,并尝试通过这样的根文件夹访问它:getClass.getResources("/folder/file.ser").getPath();.两者都可以在台式机(Windows)上正常运行,但不幸的是Android找不到按文件路径显示的文件.

I tried with new File("src/main/resources/folder/file.ser").getAbsolutePath(); and by trying to access it from my root folder like this: getClass.getResources("/folder/file.ser").getPath();. Both of them works fine on desktop (Windows) but unfortunately Android does not find the file by file path.

另一个问题可能是我不应该在资源文件夹中创建运行时文件,但是应该在哪里?

An other problem could be that I should not create runtime files in the resource folder but then where should I?

有什么主意,我该如何读写在Android和台式机上均可运行时创建的文件?

Any idea how can I read and write runtime created files that works both on android and desktop?

(如果信息不足以帮助我,我会尝试以最小的形式复制代码并提供更多详细信息.)

推荐答案

资源文件,其路径在 class路径上,可以包装在jar中,并且应该视为只读,尤其是在某些情况下可能会缓存资源时.他们不是不是 File.它们可以通过URL,URI,Path捕获.路径区分大小写,路径分隔符为/.

Resource files with a path on the class path, could be packed in a jar and should be considered read-only, especially as resources might be cached in some cases. They are not File. They can be captured by URL, URI, Path. The paths are case-sensitive and the path separator is /.

因此,资源只能用作模板(初始文件).应该将它们复制到应用程序外部的真实文件中.

Hence resources can only be used as a template, an initial file. They should be copied to a real File, outside the application.

Path path = Paths.get(System.getProperty("user.home"), ".myapp/file.ser");
Files.createDirectories(path.getParent());
if (Files.exists(path)) {
    URL url = MyClass.class.getResource("/folder/file.ser");
    Path template = Paths.get(url.toURI());

    Files.copy(template, path);
}

此外,.ser,一个序列化的Java对象,不是一个好主意.我会建议XML 使用带有注释的JAXB.更具可读性,可维护性,可版本化.在您自己的位置开发JRE与在客户端部署JRE之间没有冲突.

Furthermore .ser, a serialized java object, is not a good idea. I would suggest XML using JAXB with annotations. More readable, maintainable, versionable. No clash between development JRE at your place and deployed JRE at the client.

这篇关于Java-跨平台文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆