读取文件内容

mac2022-06-30  15

如果要打开存放在/data/data/<package name>/files目录应用私有的文件,可以使用Activity提供openFileInput()方法。 FileInputStream inStream = this.getContext().openFileInput("itcast.txt"); Log.i("FileTest", readInStream(inStream)); readInStream()的方法请看下面。   public static String readInStream(FileInputStream inStream){ try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = -1; while((length = inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, length); } outStream.close(); inStream.close(); return outStream.toString();//byte[] data=outStream.toByteArray();   //String result=new String(data); } catch (IOException e) { Log.i("FileTest", e.getMessage()); } return null; }

 

  或者直接使用文件的绝对路径: File file = new File("/data/data/cn.itcast.action/files/itcast.txt"); FileInputStream inStream = new FileInputStream(file); Log.i("FileTest", readInStream(inStream)); 注意:上面文件路径中的“cn.itcast.action”为应用所在包,当你在编写代码时应替换为你自己应用使用的包。 对于私有文件只能被创建该文件的应用访问,如果希望文件能被其他应用读和写,可以在创建文件时,指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。   Activity还提供了getCacheDir()和getFilesDir()方法: getCacheDir()方法用于获取/data/data/<package name>/cache目录 getFilesDir()方法用于获取/data/data/<package name>/files目录  

转载于:https://www.cnblogs.com/wdc224/p/3919399.html

最新回复(0)