【问题标题】:File not recognized in the given path在给定路径中无法识别文件
【发布时间】:2014-07-22 00:03:12
【问题描述】:
String inXSL="src/main/resources/abc.xslt";

这里我试图从路径名中获取文件并处理它,但文件永远不会从给定的路径(JAVA)中被识别出来。仅供参考,系统是 MAC。

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

请就此提供意见。

【问题讨论】:

  • 如果它是一个 maven 项目,您应该能够只使用 src/main/resources 目录中提供的名称访问该文件。
  • 尝试将/ 更改为File.seperator。放置文件时也要小心。在项目根目录中尝试将其放入res/file.xslt。 res 文件夹应该是你的 src and bin 文件夹的长边。
  • 显示访问该文件的代码。
  • 您还需要确保文件存在于 build/target 中。maven/ant 不会自动复制所有文件。
  • 请提供更多上下文,你在做新文件(inXSL)吗?如果是这样,你总是可以做 sysout("file:" + new File().getFilename());

标签: java eclipse file file-io


【解决方案1】:

当您的应用程序被打包和构建时,您的文件将与其他类一起放置在您的 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。

【讨论】:

  • 这个答案非常有帮助,而且很有效。非常感谢。现在我明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多