import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
/*
小练习
键盘输入文件名,文件内容,按照输入的文件名,文件内容保存。
要求输入内容的时候可以多次追加写入,以一个约定字符串表示结束输出内容,比如当输入end时表示终止内容输入。
*/
public class Work1 {
public static void main(String[] args) {
// 步骤一:创建键盘输入对象,String接收文件路径
Scanner sc = new Scanner(System.in);
System.out.println(“请输入要写入信息文件的绝对路径:”);
String filepath = sc.nextLine();
// 步骤二:创建输出流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath,true);
//步骤三:String接收输入文件内容,并转成字节数组,writer输出
String file = null;
//设置死循环,除非输入的字符串等于end
while (true) {
System.out.println(“请输入要写入的数据”);
file = sc.nextLine();
//设置循环出口
if(“end”.equals(file)){
break;
}
//将字符串转换成byte数组
byte[] bytes = file.getBytes();
fos.write(bytes);
fos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭IO资源
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
sc.close();
}
}
}
Java:键盘配合IO流写文件
最新推荐文章于 2021-07-07 10:57:42 发布