Java IO学习笔记:字符流

Java IO学习笔记:字符流
 
字符流的处理和字节流差不多,API基本上完全一样,就是计量单位不同。另外字符流还提供一些其他的处理流,比如按行读取流、字符串流等等。
 
下面给个例子看看:
 
import java.io.*;

/**
* 字符流测试
*
* @author leizhimin 2008-8-27 22:16:44
*/
public class TestIOStream {
     public static void main(String[] args) {
        testReaderWriter();
        testLineNumberReader();
    }

     /**
     * 带缓冲的字符流
     */
     public static void testReaderWriter() {
         int bufsize = 25;
         try {
            BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( "C:\\x.txt")));
            BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter( new File( "C:\\xb.txt")));

             char buf[] = new char[bufsize];     //字符缓冲区
             while (bufferedReader.read(buf) != -1) {
                bufferedWriter.write(buf);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     /**
     * 按行读取的字符流
     */
     public static void testLineNumberReader() {
         try {
            LineNumberReader lineNumberReader = new LineNumberReader( new BufferedReader( new FileReader( new File( "C:\\x.txt"))));

            String lineString;       //行字符串变量
             int x = 0;               //行号
             while ((lineString = lineNumberReader.readLine()) != null) {
                x++;
                System.out.println( "行号:" + x + " >>>" + lineString);
            }
            lineNumberReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
运行结果:
行号:1 >>>白日依山尽,黄河入海流。  
行号:2 >>>欲穷千里目,更上一层楼。
行号:3 >>>
行号:4 >>>―― 王之涣《登鹳雀楼》

Process finished with exit code 0
 
 

本文出自 “熔 岩” 博客,转载请与作者联系!

你可能感兴趣的:(java,IO,职场,休闲)