如何从类路径加载/引用文件作为File实例 [英] How to load/reference a file as a File instance from the classpath

查看:117
本文介绍了如何从类路径加载/引用文件作为File实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的类路径中的文件,例如 COM /路径/到/ file.txt的。我需要加载或引用此文件作为 java.io.File 对象。这是因为我需要使用 java.io.RandomAccessFile 访问该文件(文件很大,我需要寻找某个字节偏移量)。这可能吗? RandomAccessFile 的构造函数需要文件实例或字符串(路径)。

I have a file that is in my classpath, e.g. com/path/to/file.txt. I need to load or reference this file as a java.io.File object. The is because I need to access the file using java.io.RandomAccessFile (the file is large, and I need to seek to a certain byte offset). Is this possible? The constructors for RandomAccessFile require a File instance or String (path).

如果有另一个解决方案寻求某个字节偏移并读取该行,我也对此持开放态度。

If there's another solution to seek to a certain byte offset and read the line, I'm open to that as well.

推荐答案

尝试获取类路径资源的URL:

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

然后使用构造函数创建文件接受URI:

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

这篇关于如何从类路径加载/引用文件作为File实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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