关于文件流操作

Posted on 2008-07-19 15:43 追梦人 阅读(173) 评论(0)  编辑  收藏 所属分类: Other

/**
  * 删除文件
  * @param strPath
  */
 public static void deleteFile(String strPath){
  file = new File(strPath);
  if(file.exists()){
   file.delete();
  }else{
   log.error(strPath+"不存在");
  }
 }
 
 /**
  * 使用inputstreamreader读取文件(处理了中文和换行);
  * @param filePath
  * @return
  * @throws Exception
  */
 public static String readfile(String filePath) throws Exception
 {
  String  str = "";
  
  File f = new File(filePath);

  if(!f.exists())
  {
     return "";
  }
  
  InputStreamReader read = new InputStreamReader (new FileInputStream(f),"UTF-8");
 
  BufferedReader reader=new BufferedReader(read);
 
  String line;
 
  while ((line = reader.readLine()) != null)
  {
   str += line + "\n";
  }
  
  reader.close();
 
  return str;
 }
 
 /**
  * 使用FileInputStream读取文件(处理了空格与换行)
  * @param filePath
  * @return
  * @throws Exception
  */
 public static String readfile2(String filePath) throws Exception
 {
  String str = "";
  FileInputStream inputtextfile=new FileInputStream(filePath);
//  InputStreamReader   isr   =   new   InputStreamReader(inputtextfile,   "UTF-8");  

  int len=inputtextfile.available();

  BufferedInputStream buffer1=new BufferedInputStream(inputtextfile);
  byte bufferArray[]=new byte[len];
  int n=0;
  while((n=buffer1.read(bufferArray))!=-1)
  {
   String temp=new String(bufferArray,0,n);
   temp =  new String(temp.getBytes("GBK"), "utf-8");
   str += temp;
  }
  buffer1.close();
  inputtextfile.close();
  return str;
 }
 
 /**
  * 写入文件(中文处理)
  * @param path
  * @param text
  */
 public static void writeText(String path, String text)
 {
  try
  {
   FileOutputStream o = new FileOutputStream(path);
      o.write(text.getBytes("utf-8"));
      o.close();
   } catch(Exception e)
   {
    e.printStackTrace();
   }
 }


只有注册用户登录后才能发表评论。


网站导航: