首页 > 编程语言 > 详细

Java学习(2):将键盘录入的内容保存到指定文件中

时间:2017-07-03 20:28:05      阅读:292      评论:0      收藏:0      [点我收藏+]

要求:保存键盘录入的内容,当键盘输入end时,录入结束。

 1 /**
 2  * 保存键盘输入,并以end结束
 3  * 
 4  * @author xcx
 5  * @time 2017年6月24日下午3:32:50
 6  */
 7 public class GetData {
 8 
 9     public static void main(String[] args) throws IOException {
10         String fileName = "d:\\java\\jj\\dd.txt";// 要写入的文件路径
11         File file = new File(fileName);// 创建文件对象
12         writefile(file);
13     }
14 
15     // 向文件中写入
16     public static void writefile(File file) throws IOException {
17         // 判断是否有该文件路径
18         if (file.getParentFile().exists()) {
19             // 判断是否有这个文件,如果没有就创建它
20             if (!file.exists()) {
21                 file.createNewFile();
22             }
23             // 创建键盘录入对象
24             Scanner sc = new Scanner(System.in);
25             // 获得键盘录入字符并判断
26             String s = sc.nextLine();
27             while (!s.endsWith("end")) {
28                 // 创建输出字节流
29                 FileOutputStream fos = new FileOutputStream(file, true);
30                 // 将输出字节流转化为字符流
31                 OutputStreamWriter osw = new OutputStreamWriter(fos);
32                 // 将字符流转化为缓存模式
33                 BufferedWriter bw = new BufferedWriter(osw);
34                 // 写入
35                 bw.write(s);
36                 // 关闭输出流
37                 bw.close();
38                 osw.close();
39                 fos.close();
40                 // 再次接受键盘录入
41                 s = sc.nextLine();
42             }
43 
44         }else{
45             System.out.println("你指定的文件路径不存在,请重新检查文件路径");
46         }
47     }
48 
49 }

 

Java学习(2):将键盘录入的内容保存到指定文件中

原文:http://www.cnblogs.com/xcxfuryit/p/7112724.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!