PHP字串長度找子字串與取代字串的常用函數

PHP在字串的操作上,有非常多的相關函數可以使用,我們在這裡只介紹經常會使用到的字串操作函數。像是如何取得字串的長度、在某一個字裏面尋找子字串首次出現的位置、以及字串的取代函數...等等。這些都是在編寫程式的時候,頻繁被程式設計師使用到的基礎函數。 取得字串長度 <?...

顯示具有 Java IO操作 標籤的文章。 顯示所有文章
顯示具有 Java IO操作 標籤的文章。 顯示所有文章

2012年6月21日 星期四

Java IO讀取(read)、寫入(write)與拷貝(copy)檔案


/**
   * Java IO讀取檔案 (
java io read file)
   @param fileName
   @return
   @throws IOException
   */
  public static List<String> readFile(String fileNamethrows IOException {    
    List<String> rst = new ArrayList<String>();
    BufferedReader br = null;
    try{
      br = new BufferedReader(new FileReader(fileName));
      String in = null;
      while((in = br.readLine()) != null){
        rst.add(in);
      }
    }catch(IOException ioe){
      throw ioe;
    }finally{
      br.close();      
    }    
    return rst;
  }  
  
  /**
    Java IO寫入檔案  (java io write file)
   @param data
   @param fileName
   @throws IOException
   */
  public static void writeFile(List<String> data, String fileNamethrows IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    try{
      for(String d:data){
        bw.write(d);
        bw.newLine();        
      }
      bw.flush();
    }catch(IOException ioe){
      throw ioe;
    }finally{
      bw.close();      
    }    
  }
  
  /**
    Java IO拷貝檔案 
(java io copy file)
   @param source
   @param dest
   @throws IOException
   */
  public static void copyFile(File source, File destthrows IOException {
    InputStream fis = null;
    OutputStream fos = null;    
    try{
      fos = new FileOutputStream(dest);
      fis = new FileInputStream(source);
      byte[] b = new byte[1024];
      int off = 0;
      int len = 0;
      while((len = fis.read(b)) != -1){
        fos.write(b,off,len);        
      }
      fos.flush();
    }catch(IOException ioe){
      throw ioe;
    }finally{
      fos.close();
      fis.close();
    }
  }