/** * 一行一行讀取文件,適合字符讀取,若讀取中文字符時(shí)會(huì)出現(xiàn)亂碼 * * 流的關(guān)閉順序:先打開的后關(guān),后打開的先關(guān), * 否則有可能出現(xiàn)java.io.IOException: Stream closed異常 * * @throws IOException */ @Test public void readFile01() throws IOException { FileReader fr=new FileReader("E:/phsftp/evdokey/evdokey_201103221556.txt"); BufferedReader br=new BufferedReader(fr); String line=""; String[] arrs=null; while ((line=br.readLine())!=null) { arrs=line.split(","); System.out.println(arrs[0] + " : " + arrs[1] + " : " + arrs[2]); } br.close(); fr.close(); } /** * 一行一行讀取文件,解決讀取中文字符時(shí)出現(xiàn)亂碼 * * 流的關(guān)閉順序:先打開的后關(guān),后打開的先關(guān), * 否則有可能出現(xiàn)java.io.IOException: Stream closed異常 * * @throws IOException */ @Test public void readFile02() throws IOException { FileInputStream fis=new FileInputStream("E:/phsftp/evdokey/evdokey_201103221556.txt"); InputStreamReader isr=new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); //簡(jiǎn)寫如下 //BufferedReader br = new BufferedReader(new InputStreamReader( // new FileInputStream("E:/phsftp/evdokey/evdokey_201103221556.txt"), "UTF-8")); String line=""; String[] arrs=null; while ((line=br.readLine())!=null) { arrs=line.split(","); System.out.println(arrs[0] + " : " + arrs[1] + " : " + arrs[2]); } br.close(); isr.close(); fis.close(); } /** * 一行一行寫入文件,適合字符寫入,若寫入中文字符時(shí)會(huì)出現(xiàn)亂碼 * * 流的關(guān)閉順序:先打開的后關(guān),后打開的先關(guān), * 否則有可能出現(xiàn)java.io.IOException: Stream closed異常 * * @throws IOException */ @Test public void writeFile01() throws IOException { String[] arrs={ "zhangsan,23,FuJian", "lisi,30,ShangHai", "wangwu,43,BeiJing", "laolin,21,ChongQing", "ximenqing,67,GuiZhou" }; FileWriter fw=new FileWriter(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")); //寫入中文字符時(shí)會(huì)出現(xiàn)亂碼 BufferedWriter bw=new BufferedWriter(fw); //BufferedWriter bw=new BufferedWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8"))); for(String arr:arrs){ bw.write(arr+"\t\n"); } bw.close(); fw.close(); } /** * 一行一行寫入文件,解決寫入中文字符時(shí)出現(xiàn)亂碼 * * 流的關(guān)閉順序:先打開的后關(guān),后打開的先關(guān), * 否則有可能出現(xiàn)java.io.IOException: Stream closed異常 * * @throws IOException */ @Test public void writeFile02() throws IOException { String[] arrs={ "zhangsan,23,福建", "lisi,30,上海", "wangwu,43,北京", "laolin,21,重慶", "ximenqing,67,貴州" }; //寫入中文字符時(shí)解決中文亂碼問題 FileOutputStream fos=new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")); OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw=new BufferedWriter(osw); //簡(jiǎn)寫如下: //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( // new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8")); for(String arr:arrs){ bw.write(arr+"\t\n"); } //注意關(guān)閉的先后順序,先打開的后關(guān)閉,后打開的先關(guān)閉 bw.close(); osw.close(); fos.close(); } |
|