Java文件與io——復制文件和轉換流


字節流與字符流的區別

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

如果確認流里面只有可打印的字符,包括英文的和各種國家的文字,也包括中文,那么可以考慮字符流。由於編碼不同,多字節的字符可能占用多個字節。比如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;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM