java 文件操作

来源:互联网 发布:淘宝产品单反拍摄技巧 编辑:程序博客网 时间:2024/05/01 06:40

/**
  * 复制文件
  *
  * @param fromFilePath String 目标文件
  * @param toFilePath String 保存文件的路径
  * @return boolean 复制成功 true 出错 false
  */
   
 public static boolean copyFile(String fromFilePath,String toFilePath) throws Exception
 {
 File fromFile=new File(fromFilePath);
 File toFile=new File(toFilePath);
  
 if(!fromFile.canRead() || !fromFile.exists())
 return false;
 toFile.createNewFile();
  
 try {
 FileReader fr=new FileReader(fromFile);
 BufferedReader br=new BufferedReader(fr);
  
 FileWriter fw=new FileWriter(toFile);
 BufferedWriter bw=new BufferedWriter(fw);
  
 //PrintWriter pw=new
  
 String readLine;
 while((readLine=br.readLine())!=null)
 {
 bw.write(readLine);
 bw.newLine();
 }
 bw.close();
 br.close();
 }catch (EOFException e)
  {
 System.out.println("到达文件末尾,END OF FILE");
  }finally
  {
  return true;
  } 
 }
 
  /**
  * 复制文件
  *
  * @param fromFilePath String 目标文件
  * @param toFilePath String 保存文件的路径
  * @return void
  */ 
 public static boolean copyFile(String fromFilePath,String toFilePath) throws Exception
 {
 try{
 FileOutputStream fos=new FileOutputStream(toFilePath);
 FileInputStream fis=new FileInputStream(fromFilePath);
 byte[] buffer=new byte[fis.available()];
 fis.read(buffer);
 fos.write(buffer);
 fos.close();
 fis.close();
 return true;
 }catch(FileNotFoundException e)
 {
 System.out.println("没有找到文件");
 return false;
 }
 } 

/**
  * 打印目录下的所有文件
  * 
  * @param path String 目标文件路径
  * @param filter String 过滤条件
  * @param boolean 是否级联查找目录
  * @return void
  */
 public static void ListFile(String path,final String filter,boolean all)
 {
 if("".equals(path) || path==null)
 path=".";
 File dir=new File(path);
 if(!dir.isDirectory())
 {
 System.out.println("此路径不存在目录,请检查");
 return ;
 }
 File[] fileList;
 if(filter==null || filter.trim().length()==0)
 {
 fileList=dir.listFiles();
 }else
 {
 fileList=dir.listFiles(new FileFilter()
 {
 public boolean accept(File pathname)
 {
 return pathname.getName().indexOf(filter)!=-1;
 }
 });
 }
 for(int i=0;i<fileList.length;i++)
 {
 if(fileList[i].isDirectory())
 {
 System.out.println("dirs: "+fileList[i].getAbsolutePath());
 if(all)
 ListFile(fileList[i].getAbsolutePath(),filter,all);
 }else
 {
 System.out.println("file: "+fileList[i].getAbsolutePath());
 }
 }
 }

 /**
 * 读取文件返回字节数组
 *
 * @param file File 文件
 * @return byte[] 返回该文件的字节数组
 */
 public static byte[] File2Byte(File file)throws Exception
 {
 if(file.isDirectory())
 {
 System.out.println("该文件是个目录,拒绝访问");
 return null;
 }
 FileInputStream fis=new FileInputStream(file);
 BufferedInputStream bis=new BufferedInputStream(fis);
 byte[] buffer=new byte[1024*1024];
 int len=bis.read(buffer);
 String rs=new String(buffer,0,len);
 bis.close();
 return rs.getBytes();
 }