Tag目录:文件流

以下是与Tag “文件流” 相关联的文章

使用inputsteam 处理byte问题

byte b[] = new byte[1] ;

这个可以避免文件经过处理后文件变大的问题。 但是处理大文件时显得就相当吃力了。

于是new byte[1] 不是一个好的选择。

byte b[]=new byte[new File("E:/1.iso").length];

这个可以提高速度。 但是带来又一个问题就是。 这个一次性把文件写到缓存区。 对与小文件没有问题。 但是大文件。 恐怕就........

于是就想到了。我有针对的出来最后一次流的大小不就行了。

 

贴代码开始

public static void moveOrCopyFile(String src,String tag,boolean isMove){
  try {
   long s=System.currentTimeMillis();
   File f=new File(src);
   FileInputStream in=new FileInputStream(src);
   int fileSize=(int) f.length();
   byte b[]=null;
   new File(tag).createNewFile();
   FileOutputStream out=new FileOutputStream(tag);
   int cnt=fileSize/(1024*1024);
   //小于1M(大小根据自己的情况而定)的文件直接一次性写入。 
   if(cnt==0)
   {
    b=new byte[fileSize];
   }
   else
   {
    
    b=new byte[1024*1024];
    // 出来cnt次后 文件 跳出循环 
    while(in.read(b)!=-1)
    {
     out.write(b);
     if(--cnt==0)
     {
      break;
     }
     b=new byte[1024*1024];
    }
    //最后一次流的大小通过取模的方式得到
    b=new byte[fileSize%(1024*1024)];
   }
   //最后一次的文件写入
   in.read(b);
   out.write(b);
   // 一定要记得关闭流额。 不然其他程序那个文件无法进行操作
   in.close();
   out.close();
   System.out.println(System.currentTimeMillis()-s);
   if(isMove)
   {
    f.delete();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  //System.out.println(src);
  //System.out.println(tag);
 }

 

外面递归移动或者拷贝文件的方法就不演示了。

 

Java那些事 / 2013-12-16