类似于Java中的资源包

类似于Java中的资源包

本文介绍了如何从包中读取文件 - 类似于Java中的资源包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个word.txt文件,我已经放在一个特定的java包,并需要从同一个位置读取它。我不控制部署,所以我不知道软件包将在哪里部署。



示例位置:com / example / files / words.txt。 p>

我知道如何使用ResourceBundle类从包层次结构中读取属性文件,而不是相对/绝对路径。像 ResourceBundle.getBundle(com.example.files.words)有一些类似的常规文件,以便我可以从包层次结构读取它,而不是一些绝对/相对路径?

解决方案

可以使用 getResourceAsStream()方法(在类中定义 Class )从类路径中检索资源。如果class 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('\\\
');

String content = sb.toString();
}
}


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. I do not control the deployment, so I don't know where the packages will be deployed.

Example location: 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. 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?

解决方案

You can use the getResourceAsStream() method (defined at class Class) to retrieve resources from the class-path. If class WordReader is located in package com.example then the path to the resource file should be 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();
   }
}

这篇关于如何从包中读取文件 - 类似于Java中的资源包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:45