zoukankan      html  css  js  c++  java
  • Java学习(2):将键盘录入的内容保存到指定文件中

    要求:保存键盘录入的内容,当键盘输入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 }
  • 相关阅读:
    Rust 变量
    Rust-lang(hello world 续)
    Rust-lang(hello world)
    Java 1.8 ASM ClassReader failed to parse class file
    Sqoop使用笔记
    Jstorm
    从flume到kafka,日志收集
    vim-3-插件管理
    vim-2-使用进阶
    Git-Repo-Gerrit-1-Git介绍,安装和配置
  • 原文地址:https://www.cnblogs.com/xcxfuryit/p/7112724.html
Copyright © 2011-2022 走看看