范例:使用打印流向文件中打印数据
示例代码
public static void main(String[] args) { PrintWriter pw = null; try { pw = new PrintWriter("b.txt"); pw.print(true); pw.print('c'); pw.print(new char[] { 'd', 'g', 'g' }); pw.print(123l); pw.print(12f); pw.print(1); pw.print(45); pw.println("张三"); pw.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(pw != null) { pw.close(); } } }
结果图:
范例:从文件中读取数据并且打印在控制台
示例代码:
public static void main(String[] args) { //定义缓冲区输入流对象 BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader("a.txt")); //pw = new PrintWriter(System.out); //设置自动刷新的打印流,就不需要flush了 pw = new PrintWriter(System.out,true); String line = null; while ((line = br.readLine()) != null) { pw.println(line); //pw.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { if (pw != null) { pw.close(); } try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } }
结果图:
范例:使用打印流来复制文本文件
示例代码:
public static void main(String[] args) { BufferedReader br = null; PrintWriter pw = null; System.out.println(); try { br = new BufferedReader(new FileReader("a.txt")); pw = new PrintWriter("c.txt"); String line = null; while ((line = br.readLine()) != null) { pw.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (pw != null) { pw.close(); } if (br != null) { br.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
结果图:
如有错误,欢迎指正!