黑马程序员技术交流社区

标题: 异常02 [打印本页]

作者: _J2EE_LiXiZhen    时间: 2017-11-10 23:29
标题: 异常02
[Java] 纯文本查看 复制代码
package com.itheima.demo02;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/*使用代码实现
写一个实现把字符串中数据,写入项目根目录下的content.txt文件中

1.创建包com.itheima.level1_11
2.定义类(Test11)
3.写一个静态方法 void write(String content),在方法中
a)定义字符缓冲输出流变量BufferedWriter bw;初始值为null
b)写一个try{   }catch(IOException e){  }finally{ }代码块
c)在try{ }在代码块中       
i.创建BufferedWriter对象,绑定content.txt文件,赋值给bw
ii.调用bw的write()方法,传入content
d)在catch代码块中,打印异常信息
e)在finally代码块关闭流
i.写try{}catch(IOException ex){} 代码块
ii.在try 代码块中,如果bw!=null,调用bw.close()方法
iii.在catch代码块,打印异常信息
4.在main方法中调用write(String conent)方法*/

public class Test {
        public static void main(String[] args) {
                // 在main方法中调用write(String conent)方法
                write("content");
        }

        // 写一个静态方法 void write(String content)
        public static void write(String content) {
                // 定义字符缓冲输出流变量BufferedWriter bw;初始值为null
                BufferedWriter bw = null;
                // 创建BufferedWriter对象,绑定content.txt文件,赋值给bw
                try {
                        bw = new BufferedWriter(new FileWriter(content + ".txt"));
                } catch (IOException e) {// 在catch代码块中,打印异常信息
                        System.out.println(e);
                } finally {// 在finally代码块关闭流
                        try {
                                // 在try 代码块中,如果bw!=null,调用bw.close()方法
                                if (bw != null) {
                                        bw.close();
                                }
                        } catch (IOException e) {
                                System.out.println(e);
                        }
                }

        }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2