有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    切中要害:

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("file/test.xml").getFile());
    
  2. # 2 楼答案

    首先确保abc.xml正在复制到输出目录。然后您应该使用getResourceAsStream()

    InputStream inputStream = 
        Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");
    

    一旦你有了InputStream,你只需要把它转换成一个字符串。此资源将其详细说明:http://www.kodejava.org/examples/266.html。但是,我将摘录相关代码:

    public String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();
    
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {        
            return "";
        }
    }
    
  3. # 3 楼答案

    使用谷歌番石榴:

    import com.google.common.base.Charsets;
    import com.google.common.io.Resources;
    
    public String readResource(final String fileName, Charset charset) throws Exception {
            try {
                return Resources.toString(Resources.getResource(fileName), charset);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
    }
    

    例如:

    String fixture = this.readResource("filename.txt", Charsets.UTF_8)
    
  4. # 4 楼答案

    您可以尝试执行以下操作:

    String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
    
  5. # 5 楼答案

    假设文件中使用UTF8编码-如果不是,只需省略“UTF8”参数&;将使用 在每种情况下,基础操作系统的默认字符集

    JSE 6中的快速方法-简单和;没有第三方图书馆

    import java.io.File;
    public class FooTest {
      @Test public void readXMLToString() throws Exception {
            java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
            //Z means: "The end of the input but for the final terminator, if any"
            String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\\Z").next();
      }
    }
    

    JSE 7中的快捷方式

    public class FooTest {
      @Test public void readXMLToString() throws Exception {
            java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
            java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
            String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8"); 
      }
    

    自Java 9以来的快捷方式

    new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());
    

    不过,这两种方法都不适用于大型文件

  6. # 6 楼答案

    最后,由于Apache Commons,我找到了一个简洁的解决方案:

    package com.example;
    import org.apache.commons.io.IOUtils;
    public class FooTest {
      @Test 
      public void shouldWork() throws Exception {
        String xml = IOUtils.toString(
          this.getClass().getResourceAsStream("abc.xml"),
          "UTF-8"
        );
      }
    }
    

    工作完美。文件src/test/resources/com/example/abc.xml已加载(我正在使用Maven)

    如果将"abc.xml"替换为"/foo/test.xml",则将加载此资源:src/test/resources/foo/test.xml

    您还可以使用Cactoos

    package com.example;
    import org.cactoos.io.ResourceOf;
    import org.cactoos.io.TextOf;
    public class FooTest {
      @Test 
      public void shouldWork() throws Exception {
        String xml = new TextOf(
          new ResourceOf("/com/example/abc.xml") // absolute path always!
        ).asString();
      }
    }