您好,登錄后才能下訂單哦!
這篇文章主要介紹“Java中PrintWriter如何使用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Java中PrintWriter如何使用”文章能幫助大家解決問題。
PrintWriter 與 PrintStream 相同。PrintStream 只能接字節(jié)流,而 PrintWriter 既能接字節(jié)流又能接字符流。
PrintStream 最終輸出的總是 byte 數(shù)據(jù),而 PrintWriter 則是擴展了 Writer 接口,它的 print()/println() 方法最終輸出的是 char 數(shù)據(jù)。兩者的使用方法幾乎是一模一樣的。
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("輸入目標文件"); 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("輸入目標文件字符編碼"); String toCharset = new Scanner(System.in).nextLine(); try { copy(from, to, fromCharset, toCharset); System.out.println("復制成功"); } catch (Exception e) { System.out.println("復制失敗"); } } 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(); } }
f7 內(nèi)容為:
轉(zhuǎn)為十六進制查看。原來編碼為 UTF-8,英文單字節(jié),中文3字節(jié)
f7copy 內(nèi)容:
轉(zhuǎn)為十六進制查看?,F(xiàn)在編碼為 GBK,英文單字節(jié),中文雙字節(jié),增加了換行符
關于“Java中PrintWriter如何使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識,可以關注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。