在资产文件夹里面列出文件的异常

问题描述:

我想打印,用于测试资产文件夹里面两个文件夹的内容。在资产文件夹里面列出文件的异常

的文件夹组成:

资产

  • foo.txt的
  • foo1.txt

但该方案对我说,有没有文件。

AssetManager assetManager = getAssets(); 
      String[] files = null; 
      try { 
       files = assetManager.list(""); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } 
      for (int i = 0; i < files.length; i++) { 
       File file = new File(files[i]); 
       try { 
        Scanner scanner = new Scanner(file); 
        while (scanner.hasNextLine()) { 
         Log.e(" ", " " + scanner.next()); 
        } 
        scanner.close(); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
      } 

logcat的

10-06 19:38:16.328: W/System.err(12250): java.io.FileNotFoundException: /foo.txt: open failed: ENOENT (No such file or directory) 
10-06 19:38:16.335: W/System.err(12250): at libcore.io.IoBridge.open(IoBridge.java:416) 
10-06 19:38:16.335: W/System.err(12250): at java.io.FileInputStream.<init>(FileInputStream.java:78) 
10-06 19:38:16.343: W/System.err(12250): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) 
10-06 19:38:16.351: W/System.err(12250): at libcore.io.Posix.open(Native Method) 
10-06 19:38:16.351: W/System.err(12250): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110) 

您无法将文件类用于资产文件夹中的“文件”。这是因为File只能处理文件系统上的真实文件。相反,唯一的选择是调用资产管理器打开资产文件的输入流并从该流中读取。例子在这个论坛上多次发布。

AssetManager.list给出是资产内的相对的路径。如果您需要打开文件,则需要提供该文件的绝对路径。对于资产文件,您可以使用AssetManager.open方法。

+0

当然,没有所讨论对象的“绝对路径”,因为当它到达设备时,它不再是一个文件。 – 2014-10-06 18:12:28