Java中PrintWriter使用方法介紹
簡介
PrintWriter 與 PrintStream 相同。PrintStream 只能接字節(jié)流,而 PrintWriter 既能接字節(jié)流又能接字符流。
PrintStream 最終輸出的總是 byte 數(shù)據(jù),而 PrintWriter 則是擴(kuò)展了 Writer 接口,它的 print()/println() 方法最終輸出的是 char 數(shù)據(jù)。兩者的使用方法幾乎是一模一樣的。
文本文件的轉(zhuǎn)碼復(fù)制
public class Main { public static void main(String[] args) { System.out.println("輸入源文件"); String s = new Scanner(System.in).nextLine(); File from = new File(s); if (!from.isFile()) { System.out.println("請輸入正確的文件路徑"); return; } System.out.println("輸入目標(biāo)文件"); s = new Scanner(System.in).nextLine(); File to = new File(s); if (to.isDirectory()) { System.out.println("請輸入具體的文件路徑,不是目錄路徑"); return; } System.out.println("輸入原文件字符編碼"); String fromCharset = new Scanner(System.in).nextLine(); System.out.println("輸入目標(biāo)文件字符編碼"); String toCharset = new Scanner(System.in).nextLine(); try { copy(from, to, fromCharset, toCharset); System.out.println("復(fù)制成功"); } catch (Exception e) { System.out.println("復(fù)制失敗"); } } private static void copy(File from, File to, String fromCharset, String toCharset) throws Exception { // TODO Auto-generated method stub /** * BufferedReader * InputStreamReader,fromCharset * FileInputStream * from * * PrintWriter * OutputStreamWriter,toCharset * FileOutputStream * to * * 循環(huán)按行讀寫 * * */ BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(from), fromCharset)); PrintWriter out = new PrintWriter( new OutputStreamWriter( new FileOutputStream(to), toCharset)); String line; while ((line = in.readLine()) != null) { out.println(line); } in.close(); out.close(); } }
運(yùn)行程序
f7 內(nèi)容為:
轉(zhuǎn)為十六進(jìn)制查看。原來編碼為 UTF-8,英文單字節(jié),中文3字節(jié)
f7copy 內(nèi)容:
轉(zhuǎn)為十六進(jìn)制查看。現(xiàn)在編碼為 GBK,英文單字節(jié),中文雙字節(jié),增加了換行符
到此這篇關(guān)于Java中PrintWriter使用方法介紹的文章就介紹到這了,更多相關(guān)Java PrintWriter內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javaweb判斷當(dāng)前請求是否為移動設(shè)備訪問的方法
這篇文章主要為大家詳細(xì)介紹了javaweb判斷當(dāng)前請求是否為移動設(shè)備訪問的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05SocketIo+SpringMvc實(shí)現(xiàn)文件的上傳下載功能
這篇文章主要介紹了SocketIo+SpringMvc實(shí)現(xiàn)文件的上傳下載功能,socketIo不僅可以用來做聊天工具,也可以實(shí)現(xiàn)局域網(wǎng)。文中給出了實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-08-08一文詳解Elasticsearch和MySQL之間的數(shù)據(jù)同步問題
Elasticsearch中的數(shù)據(jù)是來自于Mysql數(shù)據(jù)庫的,因此當(dāng)數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行增刪改后,Elasticsearch中的數(shù)據(jù),索引也必須跟著做出改變。本文主要來和大家探討一下Elasticsearch和MySQL之間的數(shù)據(jù)同步問題,感興趣的可以了解一下2023-04-04關(guān)于SpringMVC的數(shù)據(jù)綁定@InitBinder注解的使用
這篇文章主要介紹了關(guān)于SpringMVC的數(shù)據(jù)綁定@InitBinder注解的使用,在SpringMVC中,數(shù)據(jù)綁定的工作是由 DataBinder 類完成的,DataBinder可以將HTTP請求中的數(shù)據(jù)綁定到Java對象中,需要的朋友可以參考下2023-07-07SpringCloud Ribbon 負(fù)載均衡的實(shí)現(xiàn)
Ribbon是一個客戶端負(fù)載均衡器,它提供了對HTTP和TCP客戶端的行為的大量控制。這篇文章主要介紹了SpringCloud Ribbon 負(fù)載均衡的實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2019-01-01