Java中PrintWriter使用方法介紹
簡介
PrintWriter 與 PrintStream 相同。PrintStream 只能接字節(jié)流,而 PrintWriter 既能接字節(jié)流又能接字符流。
PrintStream 最終輸出的總是 byte 數(shù)據(jù),而 PrintWriter 則是擴展了 Writer 接口,它的 print()/println() 方法最終輸出的是 char 數(shù)據(jù)。兩者的使用方法幾乎是一模一樣的。
文本文件的轉(zhuǎn)碼復制
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使用方法介紹的文章就介紹到這了,更多相關Java PrintWriter內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SocketIo+SpringMvc實現(xiàn)文件的上傳下載功能
這篇文章主要介紹了SocketIo+SpringMvc實現(xiàn)文件的上傳下載功能,socketIo不僅可以用來做聊天工具,也可以實現(xiàn)局域網(wǎng)。文中給出了實現(xiàn)代碼,需要的朋友可以參考下2018-08-08
一文詳解Elasticsearch和MySQL之間的數(shù)據(jù)同步問題
Elasticsearch中的數(shù)據(jù)是來自于Mysql數(shù)據(jù)庫的,因此當數(shù)據(jù)庫中的數(shù)據(jù)進行增刪改后,Elasticsearch中的數(shù)據(jù),索引也必須跟著做出改變。本文主要來和大家探討一下Elasticsearch和MySQL之間的數(shù)據(jù)同步問題,感興趣的可以了解一下2023-04-04
關于SpringMVC的數(shù)據(jù)綁定@InitBinder注解的使用
這篇文章主要介紹了關于SpringMVC的數(shù)據(jù)綁定@InitBinder注解的使用,在SpringMVC中,數(shù)據(jù)綁定的工作是由 DataBinder 類完成的,DataBinder可以將HTTP請求中的數(shù)據(jù)綁定到Java對象中,需要的朋友可以參考下2023-07-07
SpringCloud Ribbon 負載均衡的實現(xiàn)
Ribbon是一個客戶端負載均衡器,它提供了對HTTP和TCP客戶端的行為的大量控制。這篇文章主要介紹了SpringCloud Ribbon 負載均衡的實現(xiàn),感興趣的小伙伴們可以參考一下2019-01-01

