JavaIO中的Reader和writer

1.reader

package com.io.Reader;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class InputStreamReaderTest {

 /**InputStreamReader类的用法 ,主要的是用于把 字节流改变成字符流
  * @param args
  * @throws FileNotFoundException 
  */
 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub
  InputStreamReader isr=new InputStreamReader(new FileInputStream("D:/Zhou.txt"),"utf-8");
  //int data;
  //while((data=isr.read())!=-1){
  // System.out.print((char)data);
  //}
  
  
  //budderedReader类
  BufferedReader br=new BufferedReader(isr);
  System.out.println(br.readLine());
  isr.close();
 }

}



package com.io.Reader;

import java.io.IOException;
import java.io.StringReader;

public class StringReaderTest {

 /**StringReader的用法 
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  StringReader reader=new StringReader("ni hao 好");
  int data;
  while((data=reader.read()) != -1){
   System.out.println((char)data+" ");
   
  }
  reader.close();
 }
}



2.writer

package com.io.writer;

import java.io.*;

public class FileUtil {

 /**copy文件的类 字符流的运用
  * @param args
  * @throws Exception 
  */
 public void readFile(String fileName) throws Exception{
  readfile(fileName, null);
 }
 
 public void readfile(String fileName,String charsetName) throws Exception{
  InputStream in=new FileInputStream(fileName);
  InputStreamReader isr=null;
  if(charsetName==null){
   isr=new InputStreamReader(in);
  }else{
   isr=new InputStreamReader(in,charsetName);
  }
  
  BufferedReader br=new BufferedReader(isr);
  String data;
  while((data=br.readLine()) != null){
   System.out.println(data);
  }
  
  br.close();
 }
 
 public void copyFile(String from,String charsetFrom,String to,String charsetTo) throws Exception{
  InputStream in=new FileInputStream(from);
  InputStreamReader reader;
  if(charsetFrom == null){
   reader=new InputStreamReader(in);
  }else{
   reader=new InputStreamReader(in,charsetFrom);
  }
  
  BufferedReader br=new BufferedReader(reader);
  
  OutputStream out=new FileOutputStream(to);
  OutputStreamWriter write=new OutputStreamWriter(out,charsetTo);
  BufferedWriter bw=new BufferedWriter(write);
  PrintWriter pw=new PrintWriter(bw);
  String data;
  while((data=br.readLine()) !=null){
   pw.println(data);
  }
  
  pw.close();
  br.close();
 }
 
 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub
  FileUtil fileUtil=new FileUtil();
  
  fileUtil.readFile("D:/Zhou.txt");
  fileUtil.copyFile("D:/Zhouhai.txt", "utf-8", "D:/Zhou.txt", "utf-8");
  fileUtil.readFile("D:/Zhou.txt");
 }

}

 

posted on 2013-10-07 13:09  邵邵  阅读(563)  评论(0编辑  收藏  举报

淘宝美工兼职招聘