0

how can you retrieve a local file using "java.nio.file.Paths" for java 7 or any other API . I have this line of code but it returns the wrong directory format.

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);

Result when printing url is:

file:/C:/Users/username/Desktop/filedirectory/filename

Supposed to be:

file:C:/Users/username/Desktop/filedirectory/filename

How can I get rid of that first / or is this a wrong method? Copied the two URLs in a windows explorer, the first one opens a webpage and cannot display, the second one opens the file I need.

4

1 回答 1

0

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

Path path = FileSystems.getDefault().getPath(filename);
List<String> lines = Files.readAllLines(path, charset);

如果您想使用 javax.jnlp.PersistenceService,请阅读http://docs.oracle.com/javase/7/docs/jre/api/javaws/jnlp/javax/jnlp/PersistenceService.html上的文档:

仅允许应用程序访问使用基于其代码库的 URL 存储的数据。例如,给定代码库http://www.mysite.com/apps/App1/,应用程序将被允许访问相关 URL 处的数据:

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

所以似乎file:不能使用以开头的 URL。

于 2014-04-04T15:02:47.577 回答