java完成记事本功能

package day11;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 完成记事本功能
 * 要求:
 * 程序启动后,要求用户输入一个文件名,然后创建该文件,
 * 之后提示用户开始输入内容,并将用户输入的每一行内容都
 * 按行写入到该文件。
 * 当用户输入"exit"时,退出程序。
 * @author Administrator
 *
 */
class NotePad{
	String noteName;//文件名称
	/*
	 * 构造方法:以文件名为参数,并调用newNotePad()方法创建文件
	 */
	public NotePad(String noteName) throws IOException {
		super();
		this.noteName = noteName;
		newNotePad(this.noteName);
	}
	public String getNoteName() {
		return noteName;
	}
	public void setNoteName(String noteName) {
		this.noteName = noteName;
	}

	@Override
	public String toString() {
		return "note [noteName=" + noteName + "]";
	}
	/*
	 * 创建以noteName为名称的文件,并判断是否已存在
	 */
	public void newNotePad(String noteName) throws IOException {
		File file = new File(noteName);
		if(!file.exists()) {
			file.createNewFile();
			System.out.println("文件"+noteName+"创建成功");
		}else {
			System.out.println("文件"+noteName+"已存在");
		}
		
	}
	/*
	 * 文件写出方法
	 */
	public void notePrint() throws IOException {
//		PrintWriter pwPrintWriter = new PrintWriter(noteName, "UTF-8");
		
		FileOutputStream fos = new FileOutputStream(noteName);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		//自动行刷新
		PrintWriter pwPrintWriter = new PrintWriter(osw, true);
		String string = null;
		Scanner scanner = new Scanner(System.in);
		
		while(!("exit".equals( string = scanner.nextLine() ) )) {
			pwPrintWriter.println(string);
			/*
			 * 若PrintWriter具有自动行刷新功能
			 * 那么每当调用println方法后会自动
			 * flush()
			 */
		}
		System.out.println("写出结束!");
		pwPrintWriter.close();
	}
}

public class Note {
	public static void main(String[] args) throws IOException {
		System.out.println("请输入文件名:");
		Scanner scanner = new Scanner(System.in);
		
		NotePad notePad = new NotePad(scanner.nextLine());
		
		System.out.println("请开始输入内容,以exit结束:");
		notePad.notePrint();
	}
}


















 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值