A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© _J2EE_LiXiZhen 中级黑马   /  2017-11-10 23:29  /  737 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[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);
			}
		}

	}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马