1. 程式人生 > >RandomAccessFile隨機讀寫檔案操作類講解

RandomAccessFile隨機讀寫檔案操作類講解

private FileAccessI fileAccessI;
private File file = null;
private int lstart = 0;

 String dirName = "";
 System.out.println("下載時接收到的內容:" + new String(bytes));
 //建立檔案路徑
 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
       // file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), items.get(position).getName());
       dirName = Environment.getExternalStorageDirectory() + currentpageUrl + "/";
 } else {
       //file = new File(getFilesDir(), items.get(position).getName());
       dirName = getFilesDir() + currentpageUrl + "/";
 }
  File fileDir = new File(dirName);
  if(!fileDir.exists()){
       fileDir.mkdirs();
  }
 String fileName = dirName + items.get(position).getName();
 file = new File(fileName);
 if (!file.exists()) {
 try {
     file.createNewFile();
 } catch (IOException e) {
     e.printStackTrace();
   }
  }
  try {
      //分段儲存檔案到記憶體
      System.out.println("寫入的檔案路徑" + file.getAbsolutePath());

      int llen = bytes.length;
      fileAccessI = new FileAccessI(file.getAbsolutePath(), lstart);
      fileAccessI.write(bytes, lstart, llen);
      lstart += llen;
      System.out.println("lstart:" + lstart);
  } catch (IOException e) {
            e.printStackTrace();
 }