简体   繁体   English

我如何从包中读取文件-类似于Java中的资源包

[英]How do I read a file from a package - something like a resource bundle in Java

I have a words.txt file that I have put in a particular java package and would need to read it from that same location. 我有一个word.txt文件,该文件已放入特定的Java包中,需要从同一位置读取它。 I do not control the deployment, so I don't know where the packages will be deployed. 我不控制部署,所以我不知道软件包将部署在哪里。

Example location: com/example/files/words.txt . 示例位置:com / example / files / words.txt。

I know how to use the ResourceBundle class to read properties file from the package hierarchy rather than a relative/absolute path. 我知道如何使用ResourceBundle类从包层次结构而不是相对/绝对路径中读取属性文件。 like ResourceBundle.getBundle(com.example.files.words) Is there something similar for general files so that I can read it from the package hierarchy rather than some absolute/relative path? ResourceBundle.getBundle(com.example.files.words)一样,通用文件是否也有类似的东西,这样我就可以从包层次结构而不是绝对/相对路径中读取它了?

You can use the getResourceAsStream() method (defined at class Class ) to retrieve resources from the class-path. 您可以使用getResourceAsStream()方法(在Class定义)来从类路径中检索资源。 If class WordReader is located in package com.example then the path to the resource file should be files/words.txt 如果类WordReader位于包com.example则资源文件的路径应为files/words.txt

package com.example;

public class WordReader {

   public void readWords() {
     InputStream is = getClass().getResourceAsStream("files/words.txt");
     StringBuilder sb = new StringBuilder();
     for(Scanner sc = new Scanner(is); sc.hasNext(); )  
         sb.append(sc.nextLine()).append('\n');

     String content = sb.toString();
   }
}

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

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