package com.yeqc.rwfile; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; public class ReadFile { public static void main(String[] args) { File file = new File("text.txt"); if (file.exists()) { System.err.println("exist"); try { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line; while((line = br.readLine()) != null){ System.out.println(line); } br.close(); isr.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } try { File newfile = new File("newtext.txt"); FileOutputStream fos = new FileOutputStream(newfile); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); bw.write("鹅\n"); bw.write("鹅鹅鹅\n"); bw.write("曲项向天歌\n"); bw.write("白毛浮绿水\n"); bw.write("红掌拨清波\n"); bw.close(); osw.close(); fos.close(); System.out.println("写入完成"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
exist 鹅 鹅鹅鹅 曲项向天歌 白毛浮绿水 红掌拨清波 写入完成
原文地址:http://11317783.blog.51cto.com/11307783/1769478