Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用路径java 7检索本地文件_Java_Path_Java 7_Java.nio.file - Fatal编程技术网

使用路径java 7检索本地文件

使用路径java 7检索本地文件,java,path,java-7,java.nio.file,Java,Path,Java 7,Java.nio.file,如何使用Java7的“java.nio.file.path”或任何其他API检索本地文件。我有这行代码,但它返回了错误的目录格式 public static InputStream readfile(String filename) throws FileNotFoundException { persistenceService = (PersistenceService) ServiceManager.lookup(PersistenceService.class.getCanonicalN

如何使用Java7的“java.nio.file.path”或任何其他API检索本地文件。我有这行代码,但它返回了错误的目录格式

public static InputStream readfile(String filename) throws FileNotFoundException
{
persistenceService = (PersistenceService) ServiceManager.lookup(PersistenceService.class.getCanonicalName());
URL url = Paths.get(filename).toUri().toURL();
FileContents fileContents = persistenceService.get(url);
打印url时的结果为:

file:/C:/Users/username/Desktop/filedirectory/filename
应该是:

file:C:/Users/username/Desktop/filedirectory/filename
我怎样才能摆脱第一个
/
,或者这是一个错误的方法?
在windows资源管理器中复制了两个URL,第一个URL打开网页无法显示,第二个URL打开我需要的文件

如果要获取本地文件的内容,不需要使用PersistenceService,只需使用
java.nio.file.Files
类:

Path path = FileSystems.getDefault().getPath(filename);
List<String> lines = Files.readAllLines(path, charset);
Path Path=FileSystems.getDefault().getPath(文件名);
列表行=文件.readAllLines(路径,字符集);
如果要使用javax.jnlp.PersistenceService,请阅读以下文档:

应用程序只允许访问使用基于其代码库的URL存储的数据。例如,给定代码库,将允许应用程序访问关联URL处的数据:

  • http://www.mysite.com/apps/App1/
  • http://www.mysite.com/apps/
  • http://www.mysite.com/

因此,似乎不能使用以
文件:
开头的URL。

您说“结果是:”。。。这是在打印
url
时发生的吗?为什么您认为结果是错误的,
persistenceService.get(url)
抛出异常?@Duncan Yes这是在打印url时。persistenceService.get(url)抛出java.io.FileNotFoundException什么类型是
persistenceService
以及
filename
的值是多少?@Duncan我编辑了这个问题,因为我无法将代码以正确的格式放入注释中。我的方法需要从文件内容返回inputstream。如何使用java.nio.file.Files使用Files.newInputStream(路径,OpenOption…)实现这一点。它在API参考中有很好的描述,哦,如果您想在该流上创建一个BufferedReader实例,只需使用Files.newBufferedReader(路径,OpenOption…)。