在给定路径中无法识别文件

时间:2014-07-22 00:03:12

标签: java eclipse file file-io

String inXSL="src/main/resources/abc.xslt";

这里试图从路径名中获取文件并对其进行处理,但文件永远不会从给定路径(JAVA)中识别出来.FYI,系统是MAC。

该文件位于项目内的src/main/resources内。

请提供相关信息。

1 个答案:

答案 0 :(得分:0)

打包并构建应用程序时,您的文件将与其他类一起放在jar(或war)的类路径中。它应该使用资源流加载。下面是一些示例代码,可以通过从类路径加载来打印文件的内容。

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {
  public static void main(String[] args) throws InterruptedException {


    byte[] contents = new byte[1024];
    InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");
    BufferedInputStream bis = new BufferedInputStream(inStream);

    int bytesRead=0;
    String strFileContents = null;
    try {
      while( (bytesRead = bis.read(contents)) != -1){
        strFileContents = new String(contents, 0, bytesRead);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    System.out.print(strFileContents);
  }
}

重要的一点是:

InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");

根据您的使用情况,输入流将传递到您正在使用的任何API中。