字節流與字符流的區別

在所有的流操作裏,字節永遠是最基礎的。任何基於字節的操作都是正確的。無論是文本文件還是二進制的文件。

如果確認流裏面只有可打印的字符,包括英文的和各種國家的文字,也包括中文,那麼可以考慮字符流。由於編碼不同,多字節的字符可能佔用多個字節。比如GBK的漢字就佔用2個字節,而UTF-8的漢字就佔用3個字節。所以,字符流是根據指定的編碼,將1個或多個字節轉化為java裏面的unicode的字符,然後進行操作。字符操作一般使用Writer,Reader等,字節操作一般都是InputStream,OutputStream以及各種包裝類,比如BufferedInputStream和BufferedOutputStream等。

總結:如果你確認你要處理的流是可打印的字符,那麼使用字符流會看上去簡單一點。如果不確認,那麼用字節流總是不會錯的。

指定一個盤符下的文件,把該文件複製到指定的目錄下。

public class CopyFileDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args)  {
        // TODO Auto-generated method stub
        File target=new File("H:\\123.txt");
        String dest="G:\\test";
        copyFile(target,dest);
        System.out.println("文件複製成功");
    }
    /**
     * 
     * @param target 源文件,要複製的文件
     * @param dest  目標文件
     */
    public static void copyFile(File target,String dest){
        String filename=target.getName();
        //System.out.println(filename);
        File destFile=new File(dest+filename);
        try {
            //先進行輸入才能進行輸出,代碼書序不能變
            InputStream in=new FileInputStream(target);
            OutputStream out=new FileOutputStream(destFile);
            byte[] bytes=new byte[1024];
            int len=-1;
            
            while((len=in.read(bytes))!=-1){
                out.write(bytes, 0, len);
            }
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

字節字符轉換流,可以將一個字節流轉換為字符流,也可以將一個字符流轉換為字節流

OutputStreamWriter:可以將輸出的字符流轉換為字節流的輸出形式

InputStreamReader:將輸入的字節流轉換為字符流輸入形式

public class ChangeStreamDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String info=reader(System.in);
        System.out.println(info);
    }

    public static String reader(InputStream in){
        BufferedReader r=new BufferedReader(new InputStreamReader(in));
        try {
            return r.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}