I/O流精练一题——从键盘录入内容,并把内容保存到文件中。(注意:录入不仅仅只能录入一行,保证可以录入多行内容)

对于只录入一行内容进行保存,很简单,想必大家都会,先看一下只录入一行的代码:

import java.io.*;
import java.util.*;
public class Text_2 {
		public static void main(String[] args) throws IOException {
			Scanner sc = new Scanner(System.in);
			System.out.println("请输入你要录入到文件中的内容:");
			String a = sc.next();
			FileOutputStream out = new FileOutputStream("c:\\javas\\kk\\Text2.txt");
			byte [] b = a.getBytes();
			out.write(b);
		}
}

上面的代码是只能够运行一次,只能将一行代码写入到文件中去
显然是不够灵活的,那么下面看一下可以追加,可以换行,可以写多行内容到文件中去完整源代码:

package text;
//2. 从键盘录入内容,并把内容保存到文件中。
import java.io.*;
import java.util.*;
public class Text_2_2 {
		public static void main(String[] args) throws IOException {
			String fileName = "c:\\javas\\kk\\Text_2_2.txt";//要写入的文件路径
			File file = new File(fileName);
			writeFile(file);
		}

		public static void writeFile(File file) throws IOException {
			//判断是否有该文件路径
			if(file.getParentFile().exists()) {
				//判断是否有这个文件,没有就创建
				if(!file.exists()) {
					file.createNewFile();
				}
				//创建键盘录入对象
				Scanner sc = new Scanner(System.in);
				//获得键盘录入字符并判断
				System.out.print("请输入你要录入的内容:");
				String s = sc.nextLine();//这个nextLine方法可以接收空格当作字符串的内容
				//String s = sc.next();----这个不可以接收空格,空格作为一个结束标志
				while(!s.endsWith("end")) {//以“end”结尾的时候表示结束
					//创建输出字节流
					FileOutputStream fos = new FileOutputStream(file,true);
					//利用转换流将输出字节流转换为字符流
					OutputStreamWriter osw = new OutputStreamWriter(fos);
					//将字符流转换为缓冲模式
					BufferedWriter bw = new BufferedWriter(osw);
					//写入
					bw.write(s);
					//换行
					bw.newLine();
					//关闭输出流
					bw.close();
					//再次接收键盘录入
					System.out.print("请继续输出你要录入的内容:");
					s=sc.nextLine();
				}
			}else {
				System.out.println("你指定的路径不存在,请重新检查并修正");
			}
		}
}

在这里插入图片描述
在这里插入图片描述
如果你追求精致可以用上面的代码,如果你追求简介,可以用下面的代码块:

package text;
//2. 从键盘录入内容,并把内容保存到文件中。
import java.io.*;
import java.util.*;
public class Text_2_3 {
		public static void main(String[] args) throws IOException {
				Scanner sc = new Scanner(System.in);
				String str  =  null ;
				FileWriter fw = new FileWriter("c:\\javas\\kk\\Text_2_3.txt");
				BufferedWriter bw = new BufferedWriter(fw);
				while(true) {
					str=sc.next();
					if(str.equals("end"))
						break;
					bw.write(str);
					bw.newLine();
					bw.flush();
				}
				bw.close();
		}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱睡觉的小馨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值