Java读写文件示例

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class Test1 {
   public static void main(String[] args) throws Exception {
    File source = new File( "d:/data/番禺女市民为自证清白转给骗子10万块.txt");
    File target = new File( "c:/" + source.getName());
//    readFileByBytes(source, target);
//    readFileChars(source, target);
    readFileByLine(source, target);
  }

   /**
    * 以字节为单位读取文件,常用于读二进制文件,如图片\声音\影音等文件
    *    
    * @param source                 源文件
    * @param target                 目标文件
    */
   public static void readFileByBytes(File source, File target) {
    InputStream is = null;
    OutputStream os = null;
     int temp = 0;
     try {
      is = new FileInputStream(source);
      os = new FileOutputStream(target);
       while ((temp = is.read()) != -1) {
        os.write(temp);
      }
    } catch (FileNotFoundException e) {
      System.out.println( "File Not Found");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
       try {
        os.close();
        is.close();
      } catch (Exception e2) {

      }
    }
    System.out.println( "以字节为单位读取二进制文件结束");
  }

   /**
    * 以字符为单位读取文件,常用于读取文本,数字等类型文件
    *    
    * @param source
    * @param target
    */
   public static void readFileChars(File source, File target) {
    Reader reader = null;
    Writer writer = null;
     try {
      reader = new InputStreamReader( new FileInputStream(source), "GB2312");
      writer = new OutputStreamWriter( new FileOutputStream(target));
       int temp = 0;
       while ((temp = reader.read()) != -1) {
        writer.write(temp);
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
       try {
        writer.close();
        reader.close();
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
  }
    
   /**
    * 以行为单位读取文件
    */
   public static void readFileByLine(File source,File target) throws Exception{
    BufferedReader reader= null;
    BufferedWriter writer= null;
    reader= new BufferedReader( new InputStreamReader( new FileInputStream(source), "gb2312"));
    writer= new BufferedWriter( new FileWriter(target));
    String temp= null;
     while( (temp=reader.readLine()) != null ){
      System.out.println(temp);
      writer.write(temp+ "\r\n");
    }
    writer.close();
    reader.close();
  }
    
}

你可能感兴趣的:(职场,休闲,Java读写文件示例)